<?php
	
		class Admin extends CI_Controller {
		
				function __construct(){
						parent::__construct();
				}
				
				function _protect2quotes($str) {
						$str = str_replace('"', '\"', $str);
						$str = str_replace("\'", "'", $str);
						$str = str_replace("'", "\'", $str);
						return $str;
				}
				
				function make_install() {
						
						$str = '';
						$tpls = new Tpl_email();
						$fields = '';
						foreach($tpls->fields as $field) $fields .= ($fields ? ', ' : '') . "`$field`";
						$tpls->get();
						foreach($tpls as $tpl)
						{
								$values = '';
								// foreach($tpls->fields as $field) $values .= ($values ? ', ' : '') . "'".addslashes($tpl->{$field})."'";
								foreach($tpls->fields as $field) $values .= ($values ? ', ' : '') . "'".$this->_protect2quotes($tpl->{$field})."'";
								$values = preg_replace('#(http://)?my\.ecmtrader\.com/?#i', '{base_url}', $values);
								$values = preg_replace('#ecmtrader\.com#i', 'mycompany.com', $values);
								$values = preg_replace('#ECM-MT4\.exe#i', 'MT4.exe', $values);
								$values = preg_replace('#ECM\s+Trader\s+Ltd#i', '{company_name}', $values);
								$values = preg_replace('#ECM\s+Trader\s+Limited#i', '{company_name}', $values);
								$values = preg_replace('#ECM\s+Trader#i', '{company_name}', $values);
								$values = preg_replace('#3864416#i', '12345678', $values);
								$str .= '$sql_tpl_email[] = "INSERT INTO `{prefix}tpl_emails` ('.$fields.') VALUES ('.$values.');";' . "\n";
						}
						
						$str .= "\n";
						
						$tpls = new Tpl_page();
						$fields = '';
						foreach($tpls->fields as $field) $fields .= ($fields ? ', ' : '') . "`$field`";
						$tpls->get();
						foreach($tpls as $tpl)
						{
								$values = '';
								// foreach($tpls->fields as $field) $values .= ($values ? ', ' : '') . "'" . str_replace("'", "\'", addslashes($tpl->{$field}))."'";
								foreach($tpls->fields as $field) $values .= ($values ? ', ' : '') . "'".$this->_protect2quotes($tpl->{$field})."'";
								$values = preg_replace('#(http://)?my\.ecmtrader\.com/?#i', '{base_url}', $values);
								$values = preg_replace('#ecmtrader\.com#i', 'mycompany.com', $values);
								$values = preg_replace('#ECM-MT4\.exe#i', 'MT4.exe', $values);
								$values = preg_replace('#ECM\s+Trader\s+Ltd#i', '{company_name}', $values);
								$values = preg_replace('#ECM\s+Trader\s+Limited#i', '{company_name}', $values);
								$values = preg_replace('#ECM\s+Trader#i', '{company_name}', $values);
								$values = preg_replace('#3864416#i', '12345678', $values);
								$str .= '$sql_tpl_page[] = "INSERT INTO `{prefix}tpl_pages` ('.$fields.') VALUES ('.$values.');";' . "\n";
						}
						die($str);
						
						// $str = '';
						// $titles = new User_title();
						// $fields = '';
						// foreach($titles->fields as $title) $fields .= ($fields ? ', ' : '') . "`$title`";
						// $titles->get();
						// foreach($titles as $title)
						// {
								// $values = '';
								// foreach($titles->fields as $field) $values .= ($values ? ', ' : '') . "'".addslashes($title->{$field})."'";
								// $str .= '$sql_titles[] = "INSERT INTO `{prefix}titles` ('.$fields.') VALUES ('.$values.');";' . "\n";
						// }
						// die($str);
						
						// $opts = read_options('', 'ARRAY');						
						// $str = '';
						// foreach($opts as $name=>$value)
						// {
								// echo $name . "<br />";
								// $str .= '$sql_opts[] = "'.$name.'";' . "\n";
						// }
						// die($str);
						
						// $opts = read_options('', 'ARRAY');						
						// $str = '';
						// foreach($opts as $name=>$value)
						// {
								// $str .= '$sql_opt_values[] = "'.$value.'";' . "\n";
						// }
						// die($str);
						
						// $str = '';
						// $countries = new Country();
						// $fields = '';
						// foreach($countries->fields as $field) $fields .= ($fields ? ', ' : '') . "`$field`";
						// $countries->get();
						// foreach($countries as $country)
						// {
								// $values = '';
								// foreach($countries->fields as $field) $values .= ($values ? ', ' : '') . "'".addslashes($country->{$field})."'";
								// $str .= '$sql_countries[] = "INSERT INTO `{prefix}users` ('.$fields.') VALUES ('.$values.');";' . "\n";
						// }
						// die($str);
				}
				
				function cp() {
						$this->load->view('admin/color_picker');
				}
				
				function rtest(){
						$this->load->library('mt4');
						$opts = read_options('', 'OBJECT');
						
						if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
						{
								// $params = array();
								// $params['login'] 	= 66668041;
								// $params['from'] 	= time()-365*24*60*60;
								// $params['to'] 		= time()+24*60*60;
								// $resp = $this->mt4->request('getbalancesoperations', $params);
								// print_r($resp);
								$params = array();
								$params['login'] 	= 66668041;
								$params['from'] 	= time()-365*24*60*60;
								$params['to'] 		= time()+24*60*60;
								$resp = $this->mt4->request('gettradingvolume', $params);
								print_r($resp);
						}																						
				}
				
				function index(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;

						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Home');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array()));
						$this->template->write_view('content', 'admin/index', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ref_links() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;

						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Set Sub-Aff URL');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array()));
						$this->template->write_view('content', 'admin/ref_links', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function jx_ref_link() {
						if ( $this->input->is_ajax_request() && $this->input->post('name') && $this->input->post('url')) {
								$name 		= trim($this->security->xss_clean($this->input->post('name')));
								$url  		= trim($this->security->xss_clean($this->input->post('url')));
								$ib_only  	= trim($this->security->xss_clean($this->input->post('ib_only')));
								
								if(!preg_match('#^(https?:\/\/)?(www[0-9]{0,3}\.)?[a-zA-Z0-9\.-]+[a-zA-Z]{2,4}[\/a-zA-Z0-9;:\?\.%_=&\|@~-]*$#', $this->input->post('url')))
								{
										die(json_encode(array('error'=>'Invalid URL', 'field_id'=>'url')));
								}
								$ref = new Ref_link();
								$ref->name    = $name;
								$ref->url     = $url;
								$ref->ib_only = $ib_only=='yes' ? 'yes' : 'no';
								$ref->r_added = time();
								$ref->save();
								die(json_encode(array('success'=>true, 'ref_id'=>$this->db->insert_id())));
						}
				}
				
				function jx_delete_ref_link() {
						if ( $this->input->is_ajax_request() && $this->input->post('link_id')>0) {
								$cfg = $this->config->item('datamapper');
								$this->db->delete($cfg['prefix'] . 'ref_links', array('id' => (int)$this->input->post('link_id'))); 
								die(json_encode(array('success'=>true)));
						}
				}
				
				function reports() {
						$this->_auth_required();
						
						$opts = read_options('', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$users	= new User();
						$u_added = in_array('u_added', $users->fields) ? 'u_added' : (in_array('added', $users->fields) ? 'added' : '');
						// print_r($users);
						// die();
						$span	= 31;
						$ref_ts	= time()-$span*24*60*60;
						$from	= mktime(0, 0, 0, date('n',$ref_ts), date('j',$ref_ts), date('Y',$ref_ts));
						$to		= mktime(23, 59, 59, date('n',$ref_ts), date('j',$ref_ts), date('Y',$ref_ts));
						$data['reports']['span']['from'] = $from;
						$data['reports']['span']['to'] 	 = mktime(23, 59, 59, date('n',time()), date('j',time()), date('Y',time()));
						// echo date("D, d-m-Y H:i:s", $from).' - '.date("D, d-m-Y H:i:s", $to) . "<br>";
						$cnt = 0;
						do {
								$users->clear();
								$users->where($u_added.' >=', $from)->where($u_added.' <=', $to)->get();
								$data['reports']['registrations']['aggregated'][$from] = $users->result_count();
								
								$users->clear();
								$users->where('mt4_group', $opts->default_demo_group)->where($u_added.' >=', $from)->where($u_added.' <=', $to)->get();
								$data['reports']['registrations']['demo'][$from] = $users->result_count();
								
								$users->clear();
								$users->where('mt4_group', $opts->default_group)->where($u_added.' >=', $from)->where($u_added.' <=', $to)->get();
								$data['reports']['registrations']['live'][$from] = $users->result_count();
								
								$users->clear();
								$users->where('mt4_group', $opts->partner_group)->where($u_added.' >=', $from)->where($u_added.' <=', $to)->get();
								$data['reports']['registrations']['partner'][$from] = $users->result_count();
								
								$from += 24*60*60;
								$to   += 24*60*60;
								// echo date("D, d-m-Y H:i:s", $from).' - '.date("D, d-m-Y H:i:s", $to) . "<br>";
								$cnt++;
								if($cnt>=$span) break;
						} while(true);
						
						// print_r($data);
						// die();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Reports');
						$this->template->write('base_url', base_url());
						$this->template->write('no_jquery', true);
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', $data);
						$this->template->write_view('head_content', 'admin/script/header/reports', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('manage_users')));
						$this->template->write_view('content', 'admin/reports', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function test_email() {
						$opts = read_options('', 'OBJECT');  
						
						$this->load->library('email');
						$config['protocol'] 	= 'smtp';
						$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
						$config['smtp_user'] 	= $opts->smtp_user;
						$config['smtp_pass'] 	= $opts->smtp_pass;
						$config['smtp_port'] 	= $opts->smtp_port;
						$config['mailtype'] 	= 'html';
						$config['charset'] 		= 'utf-8';

						$this->email->initialize($config);
						$this->email->set_newline("\r\n");

						$this->email->from($opts->smtp_user);
						$this->email->to('holy.works01@gmail.com');
						$this->email->subject('Email Test');
						$this->email->message('Testing the email class.');

						$this->email->send();

						echo $this->email->print_debugger();
				}
				
				function logs(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						$data['logs'] 			= read_sys_logs();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'System Logs');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/manage_users', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('system')));
						$this->template->write_view('content', 'admin/logs', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function send_email(){
						$this->_auth_required();
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if(!@$acl['send_email'] OR $acl['send_email']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						$opts = read_options('company_name', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						$data['logs'] 			= read_sys_logs();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Send E-mail');
						$this->template->write('base_url', base_url());
						$this->template->write('no_jquery', true);
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/send_email', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('system')));
						$this->template->write_view('content', 'admin/send_email', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function jx_send_email() {
						if( $this->input->post('token') && $this->input->post('to') && $this->input->post('subject') && $this->input->post('message') )
						{
								$this->load->helper('file');
								$dir = './data/email/' . $this->input->post('token') . '/';
								$files = array();
								if (is_dir($dir) && $handle = opendir($dir)) {
										while (false !== ($file = readdir($handle))) {
												if(!is_dir($file))
												{
														$info = get_file_info($dir . $file);
														if($info===FALSE) continue;
														$files[$info['date']] = $dir . $info['name'];
												}
										}
								}
								if(count($files)>0) 
								{
										ksort($files);
								}
								$success = 0;
								$failed  = 0;
								
								if($this->input->post('to')=='specific')
								{
										if(!$this->input->post('rcpt_list'))
										{
												die(json_encode(array('stat'=>'error', 'field_id'=>'to', 'descr'=>'Please select users')));
										}
										$rcpts = explode('|', $this->input->post('rcpt_list'));
										if(count($rcpts)==0)
										{
												die(json_encode(array('stat'=>'error', 'field_id'=>'to', 'descr'=>'Please select users')));
										}
										
										$opts = read_options('', 'OBJECT'); 
										$this->load->library('email');
										$config['protocol'] 	= 'smtp';
										$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
										$config['smtp_user'] 	= $opts->smtp_user;
										$config['smtp_pass'] 	= $opts->smtp_pass;
										$config['smtp_port'] 	= $opts->smtp_port;
										$config['mailtype'] 	= 'html';
										$config['charset'] 		= 'utf-8';
										$config['wordwrap']  	= TRUE;
										$this->email->initialize($config);
										$this->email->set_newline("\r\n");
										if(count($files)>0)  foreach($files as $file) $this->email->attach($file);
										
										$user = new User();
										foreach($rcpts as $mt4_uid)
										{
												$mt4_uid = trim($mt4_uid);
												if($mt4_uid=='') continue;
												$user->clear();
												$user->where('mt4_uid', (int)$mt4_uid)->where('mt4_uid >', 0)->get(1);
												if($user->exists() && $user->email!='')
												{
														$subject = $this->_map_client_presets($user->id, $this->input->post('subject'));
														$subject = $this->_map_option_presets($subject);
														$message = $this->_map_client_presets($user->id, $this->input->post('message'));
														$message = $this->_map_option_presets($message);														
														$this->email->from($opts->smtp_user, $opts->company_name);
														$this->email->to($user->email);
														$this->email->subject($subject);
														$this->email->message($message);
														
														$this->email->send();
														$data = $this->email->print_debugger();
														if(preg_match('#Your message has been successfully sent#is', $data))
														{
																log_activity('Admin e-mail successfully sent to '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'send_email', 'system');
																$success++;
														}
														else
														{
																log_activity('Failure sending admin e-mail to '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'send_email', 'system');
																$failed++;
														}
														$this->email->clear();
												}
										}
								}
								elseif($this->input->post('to')=='all')
								{
										$opts = read_options('', 'OBJECT'); 
										$this->load->library('email');
										$config['protocol'] 	= 'smtp';
										$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
										$config['smtp_user'] 	= $opts->smtp_user;
										$config['smtp_pass'] 	= $opts->smtp_pass;
										$config['smtp_port'] 	= $opts->smtp_port;
										$config['mailtype'] 	= 'html';
										$config['charset'] 		= 'utf-8';
										$config['wordwrap']  	= TRUE;
										$this->email->initialize($config);
										$this->email->set_newline("\r\n");
										if(count($files)>0)  foreach($files as $file) $this->email->attach($file);
										
										$users = new User();
										$users->get();
										foreach($users as $user)
										{
												if($user->email=='') continue;
												$subject = $this->_map_client_presets($user->id, $this->input->post('subject'));
												$subject = $this->_map_option_presets($subject);
												$message = $this->_map_client_presets($user->id, $this->input->post('message'));
												$message = $this->_map_option_presets($message);														
												$this->email->from($opts->smtp_user, $opts->company_name);
												$this->email->to($user->email);
												$this->email->subject($subject);
												$this->email->message($message);
												
												$this->email->send();
												$data = $this->email->print_debugger();
												if(preg_match('#Your message has been successfully sent#is', $data))
												{
														log_activity('Admin e-mail successfully sent to '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'send_email', 'system');
														$success++;
												}
												else
												{
														log_activity('Failure sending admin e-mail to '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'send_email', 'system');
														$failed++;
												}
												$this->email->clear();
										}
								}
								die(json_encode(array('stat'=>'success', 'descr'=>"Total sent: $success\nFailure(s): $failed")));
						}
				}
				
				function select_users() {
						$this->_auth_required();
						
						$opts = read_options('', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$config['per_page'] 		= (isset($uri['per_page']) && $uri['per_page']>0) ? $uri['per_page'] : 50;
						$data['users'] = new User();
						$data['users']->order_by('id', 'asc')->get($config['per_page']);
						
						$this->load->library('pagination');
						$uri 						= $this->uri->uri_to_assoc(3);
						$config['base_url'] 		= base_url().'admin/manage_users/';
						$config['total_rows'] 		= $data['users']->count();
						$config['num_links'] 		= 8;
						$config['segment_name'] 	= 'page';
						$config['r_cur_page'] 		= 1;
						$config['ajax_func'] 		= 'jxLoadUsers(\'{page}\', true)';
						
						$this->pagination->initialize($config);
						$data['paging'] = $this->pagination->create_links();
						
						$this->load->library('template');
						$this->template->set_template('light');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Select Users');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('head_content', 'admin/script/header/select_users', array('base_url'=>base_url()));						
						$this->template->write_view('content', 'admin/select_users', $data);
						// $this->template->write_view('footer', 'admin/script/footer/manage_users', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function upload_email_file() {
						$data = array();
						
						$config['upload_path'] 		= './data/email/' . ($this->input->post('token') ? $this->input->post('token') . '/':'');
						$config['allowed_types'] 	= 'gif|jpg|jpeg|png|doc|docx|rtf|txt|pdf|zip';
						$config['max_size']			= '2000000';
						$config['encrypt_name']  	= false;
						$config['overwrite']  		= false;
						if(!is_dir($config['upload_path'])) @mkdir($config['upload_path'], 0755, true);

						$this->load->library('upload', $config);
		
						if ( isset($_FILES['email_file']['name']))
						{
							if ( ! $this->upload->do_upload('email_file'))
							{
								$data['error'] = str_replace(array('<p>','</p>'), '', $this->upload->display_errors());
							}
							else
							{								
								$data['upload_data'] = $this->upload->data();
							}
						}
						
						$this->load->view('admin/upload_email_file', $data);
				}
				
				function jx_get_email_files() {
						if($this->input->post('token'))
						{
								$dir = './data/email/' . $this->input->post('token') . '/';
								$files = array();
								$this->load->helper('file');
								$this->load->helper('number');
								if ($handle = opendir($dir)) {
									while (false !== ($file = readdir($handle))) {
											if(!is_dir($file))
											{
													$info = get_file_info($dir . $file);
													if($info===FALSE) continue;
													$files[$info['date']] = '<li>'.$info['name'] . ' ['.byte_format($info['size']).']' . ' <a href="javascript:void(0);" onclick="jx_delete_email_file(\''.$this->input->post('token').'\', \''.addslashes($info['name']).'\');">delete</a></li>';
											}
									}
								}
								$str = '';
								if(count($files)>0) 
								{
										ksort($files);
										$str = "<ol>".implode("\n", $files)."</ol>";
								}
								die(json_encode(array('stat'=>'success', 'items'=>$str)));
						}
				}
				
				function jx_delete_email_file() {
						if($this->input->post('token') && $this->input->post('file_name'))
						{
								$file = './data/email/' . $this->input->post('token') . '/' . $this->input->post('file_name');
								if(is_file($file)) @unlink($file);
								die(json_encode(array('stat'=>'success')));
						}
				}
				
				function jx_load_select_users() {
						if ( $this->input->is_ajax_request() ) {
								$cur_page 		= $this->input->post('page') ? $this->input->post('page') : 1;
								$search_query 	= $this->input->post('search_query') ? $this->input->post('search_query') : '';
								$sort_by 		= $this->input->post('sort_by') ? $this->input->post('sort_by') : 'id';
								$sort_order 	= $this->input->post('sort_order') ? $this->input->post('sort_order') : 'asc';
								
								$config['per_page'] = is_numeric($this->input->post('per_page')) ? $this->input->post('per_page') : $this->input->post('per_page');
								
								$users = new User();
								if($search_query)
								{
									$params = preg_split('#\s#is', $search_query);
									if(count($params)==0) $params[] = $search_query;
									$tmp = array();
									foreach($params as $param) if(trim($param)!='' && strlen($param)>2) $tmp[] = trim($param);
									$params = $tmp;
									$fields = array('type', 'firstname', 'lastname', 'country', 'email', 'city', 'business', 'mt4_uid', 'mirror_login_id', 'mt4_group', 'mt4_group', 'mt4_agent');
									$cnt = 0;
									
									foreach($fields as $field)
									{
										foreach($params as $param)
										{
											$cnt++;
											if($cnt==1) $users->like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
											else		$users->or_like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
										}	
									}
								}
								$offset	= 0;
								if($config['per_page']>0) $offset = ($cur_page*$config['per_page'])-$config['per_page'];
								if($offset<0) $offset = 0;
								
								$total_records = $this->_query_items_total($search_query);
								
								if($config['per_page']>0)
								{
										$users->order_by($sort_by, $sort_order)->get($config['per_page'], $offset);
								}
								else
								{
										$users->order_by($sort_by, $sort_order)->get();
								}
								
								if($users->result_count()>0)
								{
										$str = '<table class="greentable">
										<thead>
										<tr>
											<th><a href="javascript:void(0);" onclick="setFilter(\'id\', \''.($sort_by=='id'&&$sort_order=='asc'?'desc':'asc').'\');">#</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'type\', \''.($sort_by=='type'&&$sort_order=='asc'?'desc':'asc').'\');">Type</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'firstname\', \''.($sort_by=='firstname'&&$sort_order=='asc'?'desc':'asc').'\');">Name</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'country\', \''.($sort_by=='country'&&$sort_order=='asc'?'desc':'asc').'\');">Country</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'email\', \''.($sort_by=='email'&&$sort_order=='asc'?'desc':'asc').'\');">E-mail</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'phone\', \''.($sort_by=='phone'&&$sort_order=='asc'?'desc':'asc').'\');">Phone</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'mt4_uid\', \''.($sort_by=='mt4_uid'&&$sort_order=='asc'?'desc':'asc').'\');">MT4 #</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'added\', \''.($sort_by=='added'&&$sort_order=='asc'?'desc':'asc').'\');">Registered</a></th>
											<th>&nbsp;</th>
										</tr>
										</thead>
										<tbody>';	
								}
								else
								{
										$str = '';	
								}
								
								foreach($users as $user)
								{ 
									 $unf = $user->id.'|'.$user->mt4_uid.'|'.trim(addslashes($user->firstname)).'|'.trim(addslashes($user->lastname));
									 $unf = preg_replace('#\r|\n#is', '', $unf);
									 $str .= '<tr>
        <td><a name="user-'.$user->id.'"></a>'.$user->id.'</td>
        <td>'.ucfirst(strtolower($user->type)).'</td>
        <td>'.($user->firstname. ($user->firstname&&$user->lastname?' ':'') . $user->lastname).'</td>
        <td>'.$user->country.'</td>
        <td>'.$user->email.'</td>
        <td>'.$user->phone.'</td>
        <td>'.$user->mt4_uid.'</td>
        <td>'.($user->added ? date("d/m/Y h:i:s A T",$user->added) : 'N/A').'</td>
		<td class="actions">
			<a class="view" title="Add to E-mail recepients" href="javascript:void(0);" onclick="parent.userSelected(\''.$unf.'\');">add</a> 
		</td>
	</tr>';
								}
								
								$this->load->library('pagination');
								$config['base_url'] 		= base_url().'admin/manage_users/';
								$config['total_rows'] 		= $total_records;
								$config['num_links'] 		= 8;
								$config['r_cur_page'] 		= $cur_page;
								$config['ajax_func'] 		= 'jxLoadUsers(\'{page}\', true)';
						
								$this->pagination->initialize($config);
								$paging = $this->pagination->create_links();
								
								if($users->result_count()==0)
								{
									$str .= '<tr><td colspan="9">No users found.</td></tr>';
								}
								else
								{
									$str .= '<tr>
												<td colspan="9">'.$paging.'</td>
									</tr>';
								}
								
								$str .= "</tbody></table>";
								
								$ret = array(
									'stat'=>'success',
									'total'=>$total_records,
									'max_pages'=>$config['per_page']>0 ? ceil($total_records/$config['per_page']) : $config['per_page'],
									'cur_page'=>$cur_page,
									'data'=>$str
								);
								die(json_encode($ret));
						}
				}
				
				function manage_users(){
						$this->_auth_required();
						
						$opts = read_options('', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$config['per_page'] 		= (isset($uri['per_page']) && $uri['per_page']>0) ? $uri['per_page'] : 50;
						$data['users'] = new User();
						$data['users']->order_by('id', 'asc')->get($config['per_page']);
						
						$this->load->library('pagination');
						$uri 						= $this->uri->uri_to_assoc(3);
						$config['base_url'] 		= base_url().'admin/manage_users/';
						$config['total_rows'] 		= $data['users']->count();
						$config['num_links'] 		= 8;
						$config['segment_name'] 	= 'page';
						$config['r_cur_page'] 		= 1;
						$config['ajax_func'] 		= 'jxLoadUsers(\'{page}\', true)';
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$data['acl']				= $admin->exists() ? json_decode($admin->acl, true) : array();
						
						$this->pagination->initialize($config);
						$data['paging'] = $this->pagination->create_links();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Manage Users');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/manage_users', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('manage_users')));
						$this->template->write_view('content', 'admin/manage_users', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->write_view('footer', 'admin/script/footer/manage_users', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function import_users(){
						$this->_auth_required();
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if(!@$acl['user_import'] OR $acl['user_import']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						$opts = read_options('company_name', 'OBJECT'); 
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						if($this->input->post('btImport'))
						{
								$this->load->helper('string');
								$sep 	= $this->input->post('sep') ? $this->input->post('sep') : ';';
								$dir 	= './data/imports/';
								$token 	=  random_string('unique');
								while(is_dir($dir . $token))
								{
										$token = random_string('unique');
								}
								$config['upload_path'] 		= $dir . $token . '/';
								@mkdir($config['upload_path'], 0755, true);
								$config['allowed_types'] 	= 'csv';
								$config['max_size']			= '10000000';
								$this->load->library('upload', $config);
								
								if ( ! $this->upload->do_upload('csv'))
								{
										$this->upload->display_errors('<div style="color:#ff0000;">', '</div>');
										$data['error'] = $this->upload->display_errors();
								}
								else
								{
										$data = $this->upload->data();
										if($fp = fopen($config['upload_path'] . '/info.json', 'wa+')) 
										{
												fputs($fp, json_encode(array('added'=>time(), 'sep'=>$sep, 'file_name'=>@$data['file_name'])));
												fclose($fp);
										}
										redirect(base_url() . 'admin/import_users/token/' . $token);
								}
						}

						$uri = $this->uri->uri_to_assoc(1);
						if(isset($uri['token']) && $uri['token']!='')
						{
								$dir 		= './data/imports/';
								$info_file 	= $dir . $uri['token'] . '/info.json';
								$json 		= @file_get_contents($info_file);
								$items 		= json_decode($json, true);
								if(isset($items['file_name']) && isset($items['sep']))
								{
										$file_path = $dir . $uri['token'] . '/' . $items['file_name'];
										 if(is_file($file_path) && $fp = fopen($file_path, 'r'))
										{
												$line = fgets($fp, 4096);
												fclose($fp);
												$sql_cols   		= 'id,lang,type,title,firstname,lastname,country,email,password,phone,phone2,address1,address2,city,state,zip,citizenship,nid,dob_year,dob_month,dob_day,dob_ts,business,exp_securities,exp_currencies,exp_futures,exp_commodities,mt4_uid,mirror_login_id,mirror_request,mt4_group,mt4_agent,leverage,primary_acct,first_login,verify,stored_doc,signature_image,signature_image_200x122,balance,free_margin,credit,exp_forex,customers_monthly,total_accts,total_clients_funds,broker_relation,clients_countries,website,promo_material,promo_method,other_info,u_added,u_updated,user_ip,u_stat';
												$sql_cols_tmp   	= explode(',', $sql_cols);
												$data['sql_cols']['-1|extra:style="color:#fff;background-color:#ff0000;"'] = 'skip';
												foreach($sql_cols_tmp as $col) $data['sql_cols'][$col] = $col;
												$data['file_token'] = $uri['token'];
												$data['file_items'] = explode($items['sep'], $line);
										}
								}
						}
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Import Users');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/manage_users', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('manage_users')));
						$this->template->write_view('content', 'admin/import_users', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function _dtest(){
						$user = new User();
						print_r($user->fields);
				}
				
				function jx_import_users() {
						if($this->input->post('token'))
						{
								$this->load->library('encrypt');
								$this->load->library('mt4');
								$opts = read_options('', 'OBJECT');
								$this->benchmark->mark('import_start');
								
								$stat 	= array('total'=>0, 'existing'=>0, 'update'=>0, 'insert'=>0, 'sync'=>0, 'mt4_new'=>0, 'new_accounts'=>array());								
								
								$token		= $this->input->post('token');
								$dir 		= './data/imports/';
								$info_file 	= $dir . $token . '/info.json';
								$json 		= @file_get_contents($info_file);
								$file_info	= json_decode($json, true);
								if(isset($file_info['file_name']) && isset($file_info['sep']))
								{
										$file_path = $dir . $token . '/' . $file_info['file_name'];
										if(is_file($file_path) && $fp = fopen($file_path, 'r'))
										{
												$json = @file_get_contents($dir . $token . '/process.log');
												if($json!='')
												{
														$tmp = json_decode($json, true);
														if($tmp!==false)
														{
																if(isset($tmp['fpos']) && $tmp['fpos']>0) fseek($fp, $tmp['fpos']);
																$stat = array('total'=>@$tmp['total'], 'existing'=>@$tmp['existing'], 'update'=>@$tmp['update'], 'insert'=>@$tmp['insert'], 'sync'=>@$tmp['sync'], 'mt4_new'=>@$tmp['mt4_new']);
														}
												}
												
												$kmap = array();
												foreach($_POST as $k=>$v)
												{
														if(substr($k, 0, 4)=='col-')
														{
																$i = str_replace('col-', '', $k);
																if(is_numeric($i) && $i>0)
																{
																		$kmap[$i-1] = $v;
																}
														}
												}
												$tmp_i = array_search('mt4_uid', $kmap);
												
												$cfg 	  = $this->config->item('datamapper');
												$user 	  = new User();
												$ex_user  = new User();
												$tmp_user = new User();
												$lcnt 	  = $stat['total'];
												$fpos	  = null;
												while(!feof($fp))
												{
														$lcnt++;
														$line   = fgets($fp, 4096);
														// echo "line=$line\n";
														$fpos	= ftell($fp);
														if($lcnt==1 && $this->input->post('skip_header')=='yes') {
																continue;
														}
														if(trim($line)=='') continue;
														$stat['total']++;
														
														$user->clear();
														$items  = explode($file_info['sep'], $line);
														// print_r($items);
														// die();
														$cnt 	= count($items);
														if($cnt>0)
														{
																$pending 	= false;
																$mt4_uid = $tmp_i!==null && $tmp_i!==false && isset($items[$tmp_i]) ? $items[$tmp_i] : '';
																$user_id = 0;
																
																
																if($mt4_uid>0)
																{
																		$ex_user->clear();	
																		$ex_user->where('mt4_uid', (int)$mt4_uid)->get(1);
																		if($ex_user->exists())
																		{
																				$user_id = $ex_user->id;
																				$stat['existing']++;
																		}
																}		
																// echo "existing={$stat['existing']}";
																if($user_id>0 && $this->input->post('skip_existing')=='yes')
																{
																		// $json = json_encode(array('total'=>$stat['total'], 'existing'=>$stat['existing'], 'update'=>$stat['update'], 'insert'=>$stat['insert'], 'sync'=>$stat['sync'], 'mt4_new'=>$stat['mt4_new'], 'fpos'=>$fpos));
																		// @file_put_contents($dir . $token . '/process.log', $json, LOCK_EX);
																		// echo "\n--Skipped--\n\n";
																		continue;
																}
																// echo "\n--NOT Skipped--\n\n";
																
																$user_record = array();	
																for($i=0;$i<count($items);$i++)
																{
																		if(isset($kmap[$i]) && $kmap[$i]!=-1 && in_array($kmap[$i], $user->fields) && $kmap[$i]!='id')
																		{
																				$pending = true;
																				if($user_id>0)
																				{
																						if($kmap[$i]=='password') 	$user_record[$kmap[$i]] = $this->encrypt->encode($this->security->xss_clean($items[$i]));
																						else 						$user_record[$kmap[$i]] = $this->security->xss_clean($items[$i]);
																				}
																				else
																				{
																						if($kmap[$i]=='password') 	$user->{$kmap[$i]} = $this->encrypt->encode($this->security->xss_clean($items[$i]));
																						else 						$user->{$kmap[$i]} = $this->security->xss_clean($items[$i]);
																				}
																		}
																}
																// print_r($kmap);
																// die();
																
																if($pending)
																{
																		if($this->input->post('mt4_sync')=='yes' && $mt4_uid>0)
																		{
																				$info = $this->_mt4_info($mt4_uid);
																				// print_r($info);
																				// die('good!');
																				if(isset($info['email'])) $stat['sync']++;
																					
																				if(@$info['email'] && $user->email!=$info['email'])
																				{
																						if($user_id>0) 		$user_record['email'] = $this->security->xss_clean($info['email']);
																						else			    $user->email = $this->security->xss_clean($info['email']);
																				}
																				if(@$info['group'] && $user->mt4_group!=$info['group'])
																				{
																						if($user_id>0) 	   $user_record['mt4_group'] = $this->security->xss_clean($info['group']);
																						else			   $user->mt4_group = $this->security->xss_clean($info['group']);
																				}
																				if(@$info['leverage'] && $user->leverage!=$info['leverage'])
																				{
																						if($user_id>0) 	   $user_record['leverage'] = $this->security->xss_clean($info['leverage']);
																						else			   $user->leverage = $this->security->xss_clean($info['leverage']);
																				}
																				if(@$info['country'] && $user->country!=$info['country'])
																				{
																						if($user_id>0) 	   $user_record['country'] = $this->security->xss_clean($info['country']);
																						else			   $user->country = $this->security->xss_clean($info['country']);
																				}
																				if(@$info['state'] && $user->state!=$info['state'])
																				{
																						if($user_id>0) 	   $user_record['state'] = $this->security->xss_clean($info['state']);
																						else			   $user->state = $this->security->xss_clean($info['state']);
																				}
																				if(@$info['adress'] && $user->address1!=$info['adress'])
																				{
																						if($user_id>0) $user_record['address1'] = $this->security->xss_clean($info['adress']);
																						else			   $user->address1 = $this->security->xss_clean($info['adress']);
																				}
																				if(@$info['city'] && $user->city!=$info['city'])
																				{
																						if($user_id>0) 	   $user_record['city'] = $this->security->xss_clean($info['city']);
																						else			   $user->city = $this->security->xss_clean($info['city']);
																				}
																				if(@$info['zip'] && $user->zip!=$info['zip'])
																				{
																						if($user_id>0) 	   $user_record['zip'] = $this->security->xss_clean($info['zip']);
																						else			   $user->zip = $this->security->xss_clean($info['zip']);
																				}
																				if(@$info['balance']!='' && $user->balance!=$info['balance'])
																				{
																						if($user_id>0) 	   $user_record['balance'] = $this->security->xss_clean($info['balance']);
																						else			   $user->balance = $this->security->xss_clean($info['balance']);
																				}
																				if(@$info['free_margin']!='' && $user->free_margin!=$info['free_margin'])
																				{
																						if($user_id>0) 	   $user_record['free_margin'] = $this->security->xss_clean($info['free_margin']);
																						else			   $user->free_margin = $this->security->xss_clean($info['free_margin']);
																				}
																				if(@$info['agent']!='' && $user->mt4_agent!=$info['agent'])
																				{
																						if($user_id>0) 	   $user_record['mt4_agent'] = $this->security->xss_clean($info['agent']);
																						else			   $user->mt4_agent = $this->security->xss_clean($info['agent']);
																				}
																		}
																		
																		// die("-- eol");
																		
																		if($user_id>0 && $this->input->post('skip_existing')!='yes' && count($user_record)>0)
																		{
																				$user->u_updated = time();
																				$user->where('id', (int)$user_id)->update($user_record);
																				$stat['update']++;
																		}
																		elseif($user_id==0)
																		{
																				$user->type	  = trim($user->type)!='' ? strtolower(trim($user->type)) : (preg_match('#demo#is', $user->mt4_group) ? 'demo':'real');
																				$user->added  = time();
																				$user->u_stat = 'active';
																				$user->save();
																				$user_id 	  = $this->db->insert_id();
																				$stat['insert']++;
																				$stat['new_accounts'][$user_id] = array('id'=>$user_id);
																		}
																		if($mt4_uid=='' && $user_id>0)
																		{
																				if($user->password=='' OR !$this->_isValidMt4Pass($this->encrypt->decode($user->password)))
																				{
																						$user->password = $this->encrypt->encode(random_string('alnum', 10));
																						$tmp_user->clear();
																						$tmp_user->where('id', (int)$user_id)->update(array('password'=>$user->password, 'u_updated'=>time()));
																				}
																				$params 						= array();
																				$params['state'] 				= $user->state;
																				$params['email'] 				= $user->email;
																				$params['group'] 				= $user->mt4_group ? $user->mt4_group : ($user->type=='demo'?$opts->default_demo_group:(preg_match('#-IB$#i', $user->mt4_group)?$opts->partner_group:$opts->default_group));
																				$params['city'] 				= $user->city;
																				$params['password_investor'] 	= '0';
																				$params['leverage'] 		 	= 400;
																				$params['id'] 					= '';
																				$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
																				$params['country'] 				= $user->country;
																				$params['password'] 			= $this->encrypt->decode($user->password);
																				$params['password_phone'] 		= '';
																				$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
																				$params['zipcode'] 				= '';
																				$params['phone'] 				= $user->phone;
																				$params['login'] 				= 0;
																				$params['comment'] 				= (preg_match('#-IB$#i', $user->mt4_group)?'partner':$user->type) . " #$user_id";
																				$params['agent'] 				= $user->mt4_agent;
																				
																				if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
																				{
																						$resp = $this->mt4->request("createaccount", $params);
																						if($resp!==FALSE && isset($resp['result']) && $resp['result']>=0 && isset($resp['login']))
																						{
																								$user->clear();
																								$user->u_updated = time();
																								$user->where('id', (int)$user_id)->update(array('mt4_uid'=>$resp['login']));
																								$stat['mt4_new']++;
																								
																								if($this->input->post('email_notif')=='yes') $this->guess_resend_notif($user_id);
																						}
																						else
																						{
																								$stat['new_accounts'][$user_id]['error'] = @$resp['reason'];
																								$this->db->where('id', (int)$user_id);
																								$this->db->where('id >', 0);
																								$this->db->delete($cfg['prefix'] . 'users');
																								print_r($params);
																								die('error='.@$resp['reason']);
																						}
																				}
																				else
																				{
																						$stat['new_accounts'][$user_id]['error'] = $this->mt4->errstr;
																						$this->db->where('id', (int)$user_id);
																						$this->db->where('id >', 0);
																						$this->db->delete($cfg['prefix'] . 'users');
																				}
																		}
																}
																// if($lcnt>10) break;
																// $json = json_encode(array('total'=>$stat['total'], 'existing'=>$stat['existing'], 'update'=>$stat['update'], 'insert'=>$stat['insert'], 'sync'=>$stat['sync'], 'mt4_new'=>$stat['mt4_new'], 'fpos'=>$fpos));
																// @file_put_contents($dir . $token . '/process.log', $json, LOCK_EX);	
														}
												}
												fclose($fp);
												log_activity('Users import by ' . $this->_get_current_admin(), 'admin', 'user_import', 'system');
										}
								}
								$this->benchmark->mark('import_end');
								die(json_encode(array('stat'=>'success', 'result'=>$stat)));
						}
						die(json_encode(array('error'=>'Invalid parameters.')));
				}
				
				function _isValidMt4Pass($pass) {
						if ( preg_match('#[a-z]#', $pass) && (preg_match('#[A-Z]#', $pass) OR preg_match('#[0-9]#', $pass))) return true;
						elseif ( preg_match('#[A-Z]#', $pass) && (preg_match('#[a-z]#', $pass) OR preg_match('#[0-9]#', $pass))) return true;
						elseif ( preg_match('#[0-9]#', $pass) && (preg_match('#[a-z]#', $pass) OR preg_match('#[A-Z]#', $pass))) return true;
						return false;
				}
				
				function export_users() {
						$this->_auth_required();
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if(!@$acl['user_export'] OR $acl['user_export']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						$this->load->library('encrypt');
						$this->load->library('user_agent');
						$sep = ';';
						$nl = preg_match('#windows#is', $this->agent->platform()) ? "\r\n" : "\n";
						
						$users = new User();
						$users->order_by('id', 'asc')->get();
						
						$host = parse_url(base_url(),  PHP_URL_HOST);
						
						header("Pragma: no-cache");
						header("Expires: 0");
						header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
						header("Cache-Control: private",false);
						header("Content-Type: application/octet-stream");
						header("Content-Disposition: attachment; filename=Customers".($host?"_{$host}":'')."-".date('d-m-Y').".csv");
						header("Content-Transfer-Encoding: binary");						
						
						$hd = '"ID","MT4 ID","MT4 group","MT4 agent","Language","Type","Title","Firstname","Lastname","Country","E-mail","Password","Phone","Phone2","Address1","Address2","City","State","Zip Code","Citizenship","Passport ID","Birth date","Business","Experience in securities","Experience in currencies","Experience in futures","Experience in commodities","Experience in forex","Mirror login ID","Leverage","Primary account","Verified","Stored doc","Signature","Signature thumbnail","Balance","Free margin","Credit","Number of customers monthly","Present total accounts","Total clients funds","Past relation with Broker","Clients\' countries","Website","Promo material","Promotional method","Other inforation","Comment 1","Comment 2","Comment 3","Referral Name & account no.","Signup Date","Last Update","User IP"';
						echo str_replace(',', $sep, $hd) . $nl;
						
						$cnt = 0;
						foreach($users as $user)
						{
								$title   				 = is_numeric($user->title) ? $this->_fetch_user_title_by_id($user->title) : $user->title;
								$country 				 = is_numeric($user->country) ? $this->_fetch_country_by_id($user->country) : $user->country;
								$stored_doc 			 = $user->stored_doc ? $user->stored_doc : '';
								$signature_image 		 = $user->signature_image ? $user->signature_image : '';
								$signature_image_200x122 = $user->signature_image_200x122 ? $user->signature_image_200x122 : '';
								echo "{$user->id}{$sep}{$user->mt4_uid}{$sep}{$user->mt4_group}{$sep}{$user->mt4_agent}{$sep}".strtoupper($user->lang)."{$sep}".ucfirst(strtolower($user->type))."{$sep}{$title}{$sep}{$user->firstname}{$sep}{$user->lastname}{$sep}{$country}{$sep}{$user->email}{$sep}".$this->encrypt->decode($user->password)."{$sep}{$user->phone}{$sep}{$user->phone2}{$sep}".($this->_format_csv_item($sep, $user->address1))."{$sep}".($this->_format_csv_item($sep, $user->address2))."{$sep}".($this->_format_csv_item($sep, $user->city))."{$sep}{$user->state}{$sep}{$user->zip}{$sep}{$user->citizenship}{$sep}{$user->nid}{$sep}{$user->dob_month}/{$user->dob_day}/{$user->dob_year}{$sep}{$user->business}{$sep}{$user->exp_securities}{$sep}{$user->exp_currencies}{$sep}{$user->exp_futures}{$sep}{$user->exp_commodities}{$sep}{$user->exp_forex}{$sep}{$user->mirror_login_id}{$sep}{$user->leverage}{$sep}{$user->primary_acct}{$sep}{$user->verify}{$sep}{$stored_doc}{$sep}{$signature_image}{$sep}{$signature_image_200x122}{$sep}{$user->balance}{$sep}{$user->free_margin}{$sep}{$user->credit}{$sep}{$user->customers_monthly}{$sep}{$user->total_accts}{$sep}{$user->total_clients_funds}{$sep}".($this->_format_csv_item($sep, $user->broker_relation))."{$sep}".(str_replace('|', ',', $user->clients_countries))."{$sep}{$user->website}{$sep}".($this->_format_csv_item($sep, $user->promo_material))."{$sep}".($this->_format_csv_item($sep, $user->promo_method))."{$sep}".($this->_format_csv_item($sep, $user->other_info))."{$sep}{$user->comment1}{$sep}{$user->comment2}{$sep}{$user->comment3}{$sep}{$user->referral}{$sep}".($user->added>0 ? date('d-m-Y h:i A T', (int)$user->added):'')."{$sep}".($user->u_updated>0 ? date('d-m-Y h:i A T', (int)$user->u_updated) : '')."{$sep}{$user->user_ip}" . $nl;
								$cnt++;
								// if($cnt>10) break;
						}
				}
				
				function _format_csv_item($sep, $str){
						if(strstr($str, $sep))
						{
								if(strstr($str, '"')) $str = str_replace('"', '""', $str);
								$str = '"'.$str.'"';
						}
						else
						{
								if(strstr($str, '"'))  $str = str_replace('"', '""', $str);
								if(strstr($str, "\n")) $str = '"'.$str.'"';
						}
						return $str;
				}
				
				function ajax_user_resend_notif(){
						if( $this->input->is_ajax_request() && $this->input->post('user_id')) 
						{
								$user_id = $this->security->xss_clean($this->input->post('user_id'));
								$user = new User();
								$user->where('id', (int)$user_id)->get(1);
								if($user->exists())
								{
										$opts = read_options('default_demo_group,default_group,partner_group,aim_group', 'OBJECT'); 
										$this->load->library('encrypt');
										if($user->mt4_group==$opts->default_demo_group)
										{
												$this->_alert_demo_signup($user->lang, $user->id);
												log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'resend_notif', 'system');
												die(json_encode(array('stat'=>'success', 'descr'=>'E-mail successfully sent!')));
										}
										elseif($user->mt4_group==$opts->default_group)
										{
												$this->_alert_live_signup($user->lang, $user->id);
												log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'resend_notif', 'system');
												die(json_encode(array('stat'=>'success', 'descr'=>'E-mail successfully sent!')));
										}
										elseif($user->mt4_group==$opts->partner_group)
										{
												$this->_alert_partner_signup($user->lang, $user->id);
												log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'resend_notif', 'system');
												die(json_encode(array('stat'=>'success', 'descr'=>'E-mail successfully sent!')));
										}
										elseif($user->mt4_group==$opts->aim_group)
										{
												$this->_alert_aim_signup($user->lang, $user->id);
												log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'resend_notif', 'system');
												die(json_encode(array('stat'=>'success', 'descr'=>'E-mail successfully sent!')));
										}
										else
										{
												die(json_encode(array('stat'=>'error_popup', 'descr'=>'Please set this user\'s MT4 group and try it again!')));
										}
								}
								else
								{
										die(json_encode(array('stat'=>'error_popup', 'descr'=>'User #'.$user_id.' was not found in database!')));
								}
						}
				}
				
				function guess_resend_notif($user_id) {
						$user = new User();
						$user->where('id', (int)$user_id)->get(1);
						if($user->exists())
						{
								$opts = read_options('default_demo_group,default_group,partner_group', 'OBJECT'); 
								$this->load->library('encrypt');
								if($user->mt4_group==$opts->default_group)
								{
										$this->_alert_live_signup($user->lang, $user->id);
										log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'guess_resend_notif', 'system');
										return true;
								}
								if($user->mt4_group==$opts->default_demo_group)
								{
										$this->_alert_demo_signup($user->lang, $user->id);
										log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'guess_resend_notif', 'system');
										return true;
								}
								if($user->mt4_group==$opts->partner_group)
								{
										$this->_alert_partner_signup($user->lang, $user->id);
										log_activity('Signup e-mail re-sent to user #'.$user->id.' by ' . $this->_get_current_admin(), 'admin', 'guess_resend_notif', 'system');
										return true;
								}
						}
						return false;
				}
				
				function _alert_demo_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT'); 
						
						$tpl_email = new Tpl_email(); 
						$tpl_email->where('type','signup_demo_conf')->get(1);
						$user = new User(); 
						$user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Demo Signup e-mail successfully sent to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_demo_signup', 'system');
								}
								else
								{
										log_activity('Failure sending demo signup e-mail to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_demo_signup', 'system');
								}
								if($fp = fopen('./demo-email-log-txt', 'wa+'))
								{
										fputs($fp, $data);
										fclose($fp);
								}
						}
				}
				
				function _alert_live_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT'); 
						
						$tpl_email = new Tpl_email(); 
						$tpl_email->where('type','signup_live_conf')->get(1);
						$user = new User(); 
						$user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Live Signup e-mail successfully sent to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_live_signup', 'system');
								}
								else
								{
										log_activity('Failure sending live signup e-mail to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_live_signup', 'system');
								}
								if($fp = fopen('./live-email-log-txt', 'wa+'))
								{
										fputs($fp, $data);
										fclose($fp);
								}
						}
				}
				
				function _alert_partner_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT'); 
						
						$tpl_email = new Tpl_email(); 
						$tpl_email->where('type','signup_partner_conf')->get(1);
						$user = new User(); 
						$user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Partner Signup e-mail successfully sent to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_partner_signup', 'system');
								}
								else
								{
										log_activity('Failure sending partner signup e-mail to user '.$user->email.' (MT4 #'.$user->mt4_uid.')', 'admin', 'alert_partner_signup', 'system');
								}
								if($fp = fopen('./partner-email-log-txt', 'wa+'))
								{
										fputs($fp, $data);
										fclose($fp);
								}
						}
				}
				
				function _alert_aim_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT');
						
						$tpl_email = new Tpl_email(); $tpl_email->where('type','signup_aim_conf')->get(1);
						$user = new User(); $user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);
								
								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes' && substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('AIM Signup e-mail successfully sent to '.$user->email, 'user', 'aim_signup', 'system');
								}
								else
								{
										log_activity('Failure sending AIM Signup e-mail to '.$user->email, 'user', 'aim_signup', 'system');
								}
						}
				}
				
				function upload_doc() {
						$data = array();						
						if ( isset($_FILES['doc']['name']) && $this->input->post('doc_user_id') )
						{
							$user_id = $this->input->post('doc_user_id');
							$dir 	 = "./data/$user_id/";
							if(!is_dir($dir)) @mkdir($dir, 0777, true);
								
							$config['upload_path'] 		= $dir;
							$config['allowed_types'] 	= 'doc|docx|rtf|txt|pdf';
							$config['max_size']			= '20000000';
							$config['encrypt_name']  	= TRUE;
							$this->load->library('upload', $config);
							$this->upload->display_errors('', '');
								
							if ( ! $this->upload->do_upload('doc'))
							{
								$data['error'] = str_replace(array('<p>','</p>'), '', $this->upload->display_errors());
							}
							else
							{											
								$data['upload_data'] = $this->upload->data();
								$data['upload_data']['image_size_str'] = '';
								
								$user = new User(); 
								$user->where('id', (int)$user_id)
									 ->where('id >', 0)
									 ->get(1);
								if($user->exists())
								{
										$user->where('id', (int)$user_id)
											 ->where('id >', 0)
											 ->update(array(
													'stored_doc'=>$data['upload_data']['file_name'],
													'u_updated'	=>time()
											 ));
								}
							}
							
						}
						$this->load->view('admin/upload_doc', $data);	
				}
				
				function upload_sig() {
						$data = array();
						
						if ( isset($_FILES['sig']['name']) && $this->input->post('sig_user_id') )
						{
							$user_id = $this->input->post('sig_user_id');
							$dir 	 = "./data/$user_id/";
							if(!is_dir($dir)) @mkdir($dir, 0777, true);
								
							$config['upload_path'] 		= $dir;
							$config['allowed_types'] 	= 'gif|png|jpeg|jpe|jpg';
							$config['max_size']			= '20000000';
							$config['encrypt_name']  	= TRUE;
							$this->load->library('upload', $config);
							$this->upload->display_errors('', '');
								
							if ( ! $this->upload->do_upload('sig'))
							{
								$data['error'] = str_replace(array('<p>','</p>'), '', $this->upload->display_errors());
							}
							else
							{	
								$data['upload_data'] 					= $this->upload->data();
								$data['upload_data']['image_size_str'] 	= '';
								$data['upload_data']['image_200x122']  	= '';
								
								$user = new User();
								$user->where('id', (int)$user_id)
									 ->where('id >', 0)
									 ->get(1);
								if($user->exists())
								{
										if($user->signature_image && is_file("./data/$user_id/".$user->signature_image))
										{
												@unlink("./data/$user_id/".$user->signature_image);
										}
										if($user->signature_image_200x122 && is_file("./data/$user_id/".$user->signature_image_200x122))
										{
												@unlink("./data/$user_id/".$user->signature_image_200x122);
										}
										$user->clear();
										$user->where('id',$user_id)
											 ->where('id >', 0)
											 ->update(array(
													'signature_image' => @$data['upload_data']['file_name']
											));
										$thumb = '';
										if($data['upload_data']['full_path'] && is_file($data['upload_data']['full_path']))
										{
												$config['image_library'] 	= 'gd2';
												$config['source_image']  	= $data['upload_data']['full_path'];
												$config['create_thumb'] 	= TRUE;
												$config['thumb_marker'] 	= '_200x122';
												$config['maintain_ratio'] 	= TRUE;
												$config['width'] 			= 200;
												$config['height'] 			= 122;
												$config['quality'] 			= 100;
												$this->load->library('image_lib', $config);
												
												if ( $this->image_lib->resize())
												{
														$thumb = basename($data['upload_data']['file_name'], $data['upload_data']['file_ext']).'_200x122'.$data['upload_data']['file_ext'];
														$user->clear();
														$user->where('id',$user_id)
															 ->where('id >', 0)
															 ->update(array(
																	'signature_image_200x122' => $thumb
															 ));
														$data['upload_data']['image_200x122']  	= $thumb;	 
												}
												else
												{
														$thumb = @$data['upload_data']['file_name'];
												}
										}
								}
							}
						}
						$this->load->view('admin/upload_sig', $data);	
				}
				
				function manage_users_backup(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$config['per_page'] 		= (isset($uri['per_page']) && $uri['per_page']>0) ? $uri['per_page'] : 50;
						$data['users'] = new User();
						$data['users']->order_by('id', 'asc')->get($config['per_page']);
						
						$this->load->library('pagination');
						$uri 						= $this->uri->uri_to_assoc(3);
						$config['base_url'] 		= base_url().'admin/manage_users/';
						$config['total_rows'] 		= $data['users']->count();
						$config['num_links'] 		= 8;
						$config['segment_name'] 	= 'page';
						$config['r_cur_page'] 		= 1;
						$config['ajax_func'] 		= 'jxLoadUsers(\'{page}\', true)';
						
						$this->pagination->initialize($config);
						$data['paging'] = $this->pagination->create_links();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Manage Users');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/manage_users', array('base_url'=>base_url()));						
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('manage_users')));
						$this->template->write_view('content', 'admin/manage_users', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->write_view('footer', 'admin/script/footer/manage_users', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function manage_banners() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['banners'] = new Banner();
						$data['banners']->order_by('id', 'desc')->get();
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Manage Banners');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/manage_banners', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ajax_delete_banner() {
						if( $this->input->is_ajax_request() && $this->input->post('banner_id')) 
						{
								$banner = new Banner();
								$banner->where('id', (int)$this->input->post('banner_id'))
									   ->where('id >', 0)
									   ->get(1);
								if($banner->exists())
								{
										$cfg = $this->config->item('datamapper');
										$this->db->delete($cfg['prefix'] . 'banners', array('id' => (int)$this->input->post('banner_id'))); 
										log_activity('Banner #'.$this->input->post('banner_id').' removed by '.$this->_get_current_admin(), 'admin', 'banner', 'system');
								}
								die(json_encode(array('stat'=>'success')));
						}
				}
								
				function embed_banner() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['banners'] = new Banner();
						$data['banners']->order_by('id', 'desc')->get();
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Embed Banner');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/embed_banner', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function embed_text_link() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['links'] = new Text_link();
						$data['links']->order_by('id', 'desc')->get();
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Embed Text Link');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/embed_text_link', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function add_banner() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Add Banner');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/add_banner', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ajax_add_banner() {
						if( $this->input->is_ajax_request() && $this->input->post('name') && $this->input->post('dest') && $this->input->post('width') && $this->input->post('height') ) 
						{
								 $name 		= trim($this->security->xss_clean($this->input->post('name')));
								 $dest 		= trim($this->security->xss_clean($this->input->post('dest')));
								 $alt 		= trim($this->security->xss_clean($this->input->post('alt')));
								 $width 	= (int)$this->input->post('width');
								 $height 	= (int)$this->input->post('height');
								 $target 	= trim($this->security->xss_clean($this->input->post('target')));
								 
								 $banner 			= new Banner();
								 $banner->name 		= $name;
								 $banner->dest 		= $dest;
								 $banner->alt 		= $alt;
								 $banner->width 	= $width;
								 $banner->height 	= $height;
								 $banner->target 	= $target;
								 $banner->b_added 	= time();
								 $banner->save();
								 $banner_id = $this->db->insert_id();
								 
								log_activity('Banner #'.$banner_id.' added by '.$this->_get_current_admin(), 'admin', 'banner', 'system');

								die(json_encode(array(
										'stat'		=>'success',
										'banner_id'	=>$banner_id
								 ) ));
						}
				}
				
				function ajax_save_banner() {
						if( $this->input->is_ajax_request()&& $this->input->post('banner_id') && $this->input->post('name') && $this->input->post('dest') && $this->input->post('width') && $this->input->post('height') ) 
						{
								 $banner_id = (int)$this->input->post('banner_id');
								 $name 		= trim($this->security->xss_clean($this->input->post('name')));
								 $dest 		= trim($this->security->xss_clean($this->input->post('dest')));
								 $alt 		= trim($this->security->xss_clean($this->input->post('alt')));
								 $width 	= (int)$this->input->post('width');
								 $height 	= (int)$this->input->post('height');
								 $target 	= trim($this->security->xss_clean($this->input->post('target')));
								 
								 $banner 	= new Banner();
								 $banner->where('id', $banner_id)
										->where('id >', 0)
										->get(1);
								 if($banner->exists())
								 {
										 $banner->where('id', $banner_id)
												->where('id >', 0)
												->update(array(
													 'name' 	=> $name,
													 'dest' 	=> $dest,
													 'alt' 		=> $alt,
													 'width' 	=> $width,
													 'height' 	=> $height,
													 'target' 	=> $target,
													 'b_updated' 	=> time()
												));
										log_activity('Banner #'.$banner_id.' updated by '.$this->_get_current_admin(), 'admin', 'banner', 'system');
								 }
								 
								 die(json_encode(array(
										'stat'		=>'success',
										'banner_id'	=>$banner_id
								 ) ));
						}
				}				
				
				function ajax_save_text_link() {
						if( $this->input->is_ajax_request()&& $this->input->post('link_id') && $this->input->post('name') && $this->input->post('text') && $this->input->post('dest') ) 
						{
								 $link_id = (int)$this->input->post('link_id');
								 $name 		= trim($this->security->xss_clean($this->input->post('name')));
								 $text 		= trim($this->security->xss_clean($this->input->post('text')));
								 $dest 		= trim($this->security->xss_clean($this->input->post('dest')));
								 $alt 		= trim($this->security->xss_clean($this->input->post('alt')));
								 $target 	= trim($this->security->xss_clean($this->input->post('target')));
								 
								 $link 	= new Text_link();
								 $link->where('id', $link_id)
										->where('id >', 0)
										->get(1);
								 if($link->exists())
								 {
										$link->where('id', $link_id)
											->where('id >', 0)
											->update(array(
												 'name' 	=> $name,
												 'text' 	=> $text,
												 'alt' 		=> $alt,
												 'target' 	=> $target,
												 't_updated' => time()
											));
										log_activity('Text link #'.$link_id.' updated by '.$this->_get_current_admin(), 'admin', 'text_link', 'system');
								 }								 
								 
								 die(json_encode(array(
										'stat'		=>'success',
										'link_id'	=>$link_id
								 ) ));
						}
				}	
				
				function edit_banner() {
						$this->_auth_required();
						
						$uri = $this->uri->uri_to_assoc(3);
						if(!isset($uri['id'])) redirect(base_url() . 'admin/manage_banners');
						
						$data 			   = array();
						$banner_id 		   = (int)$uri['id'];
						$data['banner']    = new Banner();
						$data['banner']->where('id', $banner_id)
									   ->where('id >', 0)
									   ->get(1);
						if(!$data['banner']->exists()) redirect(base_url() . 'admin/manage_banners');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Edit Banner'.($data['banner']->name?' &gt; ' . $data['banner']->name:''));
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/edit_banner', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function manage_text_links() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['links'] = new Text_link();
						$data['links']->order_by('id', 'desc')->get();
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Manage Text Links');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/manage_text_links', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ajax_delete_text_link() {
						if( $this->input->is_ajax_request() && $this->input->post('link_id')) 
						{
								$link = new Text_link();
								$link->where('id', (int)$this->input->post('link_id'))
									   ->where('id >', 0)
									   ->get(1);
								if($link->exists())
								{
										$cfg = $this->config->item('datamapper');
										$this->db->delete($cfg['prefix'] . 'text_links', array('id' => (int)$this->input->post('link_id'))); 
										log_activity('Text link #'.$this->input->post('link_id').' removed by '.$this->_get_current_admin(), 'admin', 'text_link', 'system');
								}
								die(json_encode(array('stat'=>'success')));
						}
				}
				
				function add_text_link() {
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Add Text Link');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/add_text_link', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ajax_add_text_link() {
						if( $this->input->is_ajax_request() && $this->input->post('name') && $this->input->post('text') && $this->input->post('dest') ) 
						{
								 $name 		= trim($this->security->xss_clean($this->input->post('name')));
								 $text 		= trim($this->security->xss_clean($this->input->post('text')));
								 $dest 		= trim($this->security->xss_clean($this->input->post('dest')));
								 $alt 		= trim($this->security->xss_clean($this->input->post('alt')));
								 $target 	= trim($this->security->xss_clean($this->input->post('target')));
								 
								 $text_link 			= new Text_link();
								 $text_link->name 		= $name;
								 $text_link->text 		= $text;
								 $text_link->dest 		= $dest;
								 $text_link->alt 		= $alt;
								 $text_link->target 	= $target;
								 $text_link->t_added 	= time();
								 $text_link->save();
								 $link_id 				= $this->db->insert_id();
								 
								 log_activity('Text link #'.$link_id.' added by '.$this->_get_current_admin(), 'admin', 'text_link', 'system');

								 die(json_encode(array(
										'stat'		=>'success',
										'link_id'	=>$link_id
								 ) ));
						}
				}
				
				function edit_text_link() {
						$this->_auth_required();
						
						$uri = $this->uri->uri_to_assoc(3);
						if(!isset($uri['id'])) redirect(base_url() . 'admin/manage_text_links');
						
						$data 			   = array();
						$link_id 		   = (int)$uri['id'];
						$data['link']    = new Text_link();
						$data['link']->where('id', $link_id)
									   ->where('id >', 0)
									   ->get(1);
						if(!$data['link']->exists()) redirect(base_url() . 'admin/manage_text_links');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
												
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Edit Link'.($data['link']->name?' &gt; ' . $data['link']->name:''));
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('affiliate')));
						$this->template->write_view('content', 'admin/edit_text_link', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function users_downline() {						
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;						
						
						$data['root_count'] 	= $this->_tree_root_count();
						$data['downline'] 		= $this->_user_refs_tree();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Downline');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('manage_users')));
						$this->template->write_view('content', 'admin/users_downline', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function _user_refs_tree_bck($mt4_uid=null, $level = 1) {
						$this->load->helper('string');
						$ret = '';
						if($mt4_uid==null)
						{
								echo "<ol>\n";
								$cfg = $this->config->item('datamapper');
								$query = $this->db->query("SELECT id,firstname,lastname,mt4_uid, mt4_agent 
												   FROM " . $cfg['prefix'] . "users 
												   WHERE mt4_agent = '0' AND mt4_uid>0 AND mt4_uid
												   IN (select DISTINCT mt4_agent from " . $cfg['prefix'] . "users)");
								$users = $query->result();
								// print_r($users);
								foreach($users as $user) {
										if($user->mt4_uid==0 OR $user->mt4_uid=='') continue;
										echo repeater("\t", $level+3) . '<li id="phtml_'.$user->id.'">' . "\n";
										echo repeater("\t", $level+4) . '<a href="#">'.($user->firstname . ($user->firstname && $user->lastname?' ':'') . $user->lastname).'</a>' . "\n";
										$children = new User();
										$children->where('mt4_agent', $user->mt4_uid)->get();
										if($children->result_count()>0)
										{
												echo repeater("\t", $level+4) . "<ol>\n";
												$this->_user_refs_tree($user->mt4_uid, $level+1);
												echo repeater("\t", $level+4) . "</ol>\n";
										}
										echo repeater("\t", $level+3) . "</li>\n";
								}
								echo "</ol>\n";
						}
						else
						{
								$users = new User();
								$users->where('mt4_agent', $mt4_uid)->get();
								foreach($users as $user)
								{
										if($user->mt4_uid==0 OR $user->mt4_uid=='') continue;
										echo repeater("\t", $level+4) . '<li id="phtml_'.$user->id.'">' . "\n";
										echo repeater("\t", $level+4) . '<a href="#">'.($user->firstname . ($user->firstname && $user->lastname?' ':'') . $user->lastname).'</a>' . "\n";
										$children = new User();
										$children->where('mt4_agent', $user->mt4_uid)->get();
										if($children->result_count()>0)
										{
												echo repeater("\t", $level+4) . "<ol>\n";
												$this->_user_refs_tree($user->mt4_uid, $level+1);
												echo repeater("\t", $level+4) . "</ol>\n";
										}
										echo repeater("\t", $level+4) . "</li>\n";
								}
						}
						// die();
						return $ret;
				}
				
				function _tree_root_count() {
						$cfg = $this->config->item('datamapper');
						$query = $this->db->query("SELECT id,firstname,lastname,mt4_uid, mt4_agent 
												   FROM " . $cfg['prefix'] . "users 
												   WHERE mt4_agent = '0' AND mt4_uid>0 AND mt4_uid
												   IN (select DISTINCT mt4_agent from " . $cfg['prefix'] . "users)");
						return $query->num_rows();
				}
				
				function _user_refs_tree($mt4_uid=null, $level = 1) {
						$this->load->helper('string');
						$ret = '';
						if($mt4_uid==null)
						{
								$ret .= "<ul>\n";
								$cfg = $this->config->item('datamapper');
								$query = $this->db->query("SELECT id,firstname,lastname,mt4_uid, mt4_agent 
												   FROM " . $cfg['prefix'] . "users 
												   WHERE mt4_agent = '0' AND mt4_uid>0 AND mt4_uid
												   IN (select DISTINCT mt4_agent from " . $cfg['prefix'] . "users)");
								$users = $query->result();
								foreach($users as $user) {
										if($user->mt4_uid==0 OR $user->mt4_uid=='') continue;
										$children = new User();
										$children->where('mt4_agent', $user->mt4_uid)->get();
										$ret .= repeater("\t", $level+3) . '<li id="phtml_'.$user->id.'">' . "\n";
										$ret .= repeater("\t", $level+4) . '<a href="#">'.($user->firstname . ($user->firstname && $user->lastname?' ':'') . $user->lastname).' ('.$children->result_count().')</a>' . "\n";
										if($children->result_count()>0)
										{
												$ret .= repeater("\t", $level+4) . "<ul>\n";
												$ret .= $this->_user_refs_tree($user->mt4_uid, $level+1);
												$ret .= repeater("\t", $level+4) . "</ul>\n";
										}
										$ret .= repeater("\t", $level+3) . "</li>\n";
								}
								$ret .= "</ul>\n";
						}
						else
						{
								$users = new User();
								$users->where('mt4_agent', $mt4_uid)->get();
								foreach($users as $user)
								{
										if($user->mt4_uid==0 OR $user->mt4_uid=='') continue;
										$children = new User();
										$children->where('mt4_agent', $user->mt4_uid)->get();
										$ret .= repeater("\t", $level+4) . '<li id="phtml_'.$user->id.'">' . "\n";
										$ret .= repeater("\t", $level+4) . '<a href="#">'.($user->firstname . ($user->firstname && $user->lastname?' ':'') . $user->lastname).' ('.$children->result_count().')</a>' . "\n";
										if($children->result_count()>0)
										{
												$ret .= repeater("\t", $level+4) . "<ul>\n";
												$ret .= $this->_user_refs_tree($user->mt4_uid, $level+1);
												$ret .= repeater("\t", $level+4) . "</ul>\n";
										}
										$ret .= repeater("\t", $level+4) . "</li>\n";
								}
						}
						return $ret;
				}
				
				function manage_admins() {
						$this->_auth_required();
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if(@$acl['admin_create']!='yes' AND @$acl['admin_edit']!='yes' AND @$acl['admin_delete']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['admins'] = new Gmadmin();
						$data['admins']->get();
						
						$data['acl'] = $acl;
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Manage Users');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('settings')));
						$this->template->write_view('content', 'admin/manage_admins', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						// $this->template->write_view('footer', 'admin/script/footer/manage_users', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function edit_admin() {
						$this->_auth_required();
						
						$uri = $this->uri->uri_to_assoc(1);
						if(!@$uri['id']) redirect(base_url() . 'admin/manage_admins');
						
						$data = array();
						
						$data['account'] = new Gmadmin();
						$data['account']->where('id', (int)$uri['id'])->get(1);
						if(!$data['account']->exists()) redirect(base_url() . 'admin/manage_admins');
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if(@$acl['admin_edit']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						if($a_id==$uri['id'])
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#0000ff;font-weight:bold;\">You cannot update your information from this view!<br />Instead you are being redirected to your account info page...</p><script type='text/javascript'>setTimeout('window.location = \"".base_url()."admin/account_info/\";',3000);</script>");
								redirect(base_url() . 'admin/');
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Update Admin Info');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('settings')));
						$this->template->write_view('content', 'admin/edit_admin', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function ajax_edit_admin(){
						if ( $this->input->is_ajax_request() && $this->input->post('admin_id') && $this->input->post('username') && $this->input->post('acl') ) {
								
								$admin = new Gmadmin();
								$admin->where('id', (int)$this->input->post('admin_id'))->get(1);
								if(!$admin->exists())
								{
										die(json_encode(array('stat'=>'error', 'field_id'=>'username', 'descr'=>'this user does not exist in database')));
								}
								$admin->clear();
								
								$admin->where('id !=', (int)$this->input->post('admin_id'))
									  ->where('username', trim($this->security->xss_clean($this->input->post('username'))))->get(1);
								if($admin->exists())
								{
										die(json_encode(array('stat'=>'error', 'field_id'=>'username', 'descr'=>'this username is already in use')));
								}
								$admin->clear();
								
								$record = array();
								$record['username'] = trim($this->security->xss_clean($this->input->post('username')));
								if($this->input->post('password'))
								{
										$record['password'] = $this->encrypt->encode(trim($this->security->xss_clean($this->input->post('password'))));
								}
								$record['email'] = trim($this->security->xss_clean($this->input->post('email')));
								if($this->input->post('acl'))
								{
										$json = json_encode($this->input->post('acl'));
										$record['acl'] = trim($this->security->xss_clean($json));
								}
								$record['a_updated'] 	= time();
								$admin->where('id', (int)$this->input->post('admin_id'))->update($record);
								
								log_activity('Admin [#'.$this->input->post('admin_id').' '.$admin->username.'] account updated by '.$this->_get_current_admin(), 'admin', 'admin', 'system');
								
								die(json_encode(array('stat'=>'success', 'id'=>$this->input->post('admin_id'))));
						}
						die(json_encode(array('stat'=>'error', 'descr'=>'Missing parameters')));
				}
				
				function ajax_add_admin() {
						if ( $this->input->is_ajax_request() && $this->input->post('username') && $this->input->post('password') ) {
								
								$admin = new Gmadmin();
								$admin->where('username', trim($this->security->xss_clean($this->input->post('username'))))->get(1);
								if($admin->exists())
								{
										die(json_encode(array('stat'=>'error', 'field_id'=>'username', 'descr'=>'this username is already in use')));
								}
								$admin->clear();
								
								$admin->username 	= trim($this->security->xss_clean($this->input->post('username')));
								$admin->password 	= $this->encrypt->encode(trim($this->security->xss_clean($this->input->post('password'))));
								$admin->email 		= trim($this->security->xss_clean($this->input->post('email')));
								if($this->input->post('acl'))
								{
										$json = json_encode($this->input->post('acl'));
										$admin->acl = trim($this->security->xss_clean($json));
								}
								$admin->a_added 	= time();
								$admin->save();
								$id = $this->db->insert_id();
								
								log_activity('Admin [#'.$id.' '.$admin->username.'] account created by '.$this->_get_current_admin(), 'admin', 'admin', 'system');
								
								die(json_encode(array('stat'=>'success', 'id'=>$id)));
						}
				}
				
				function _query_items_total($search_query) {
						$users = new User();
						if($search_query)
						{
								$params = preg_split('#\s#is', $search_query);
								if(count($params)==0) $params[] = $search_query;
								$tmp = array();
								foreach($params as $param) if(trim($param)!='' && strlen($param)>2) $tmp[] = trim($param);
								$params = $tmp;
								$fields = array('type', 'firstname', 'lastname', 'country', 'email', 'city', 'business', 'mt4_uid', 'mirror_login_id', 'mt4_group', 'mt4_group', 'mt4_agent');
								$cnt = 0;
									
								foreach($fields as $field)
								{
									foreach($params as $param)
									{
										$cnt++;
										if($cnt==1) $users->like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
										else		$users->or_like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
									}	
								}
						}
						$users->get();
						return $users->result_count();
				}
				
				function jx_load_users() {
						if ( $this->input->is_ajax_request() ) {
								$cur_page 		= $this->input->post('page') ? $this->input->post('page') : 1;
								$search_query 	= $this->input->post('search_query') ? $this->input->post('search_query') : '';
								$sort_by 		= $this->input->post('sort_by') ? $this->input->post('sort_by') : 'id';
								$sort_order 	= $this->input->post('sort_order') ? $this->input->post('sort_order') : 'asc';
								
								$config['per_page'] = is_numeric($this->input->post('per_page')) ? $this->input->post('per_page') : $this->input->post('per_page');
								
								$users = new User();
								if($search_query)
								{
									$params = preg_split('#\s#is', $search_query);
									if(count($params)==0) $params[] = $search_query;
									$tmp = array();
									foreach($params as $param) if(trim($param)!='' && strlen($param)>2) $tmp[] = trim($param);
									$params = $tmp;
									$fields = array('type', 'firstname', 'lastname', 'country', 'email', 'city', 'business', 'mt4_uid', 'mirror_login_id', 'mt4_group', 'mt4_group', 'mt4_agent');
									$cnt = 0;
									
									foreach($fields as $field)
									{
										foreach($params as $param)
										{
											$cnt++;
											if($cnt==1) $users->like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
											else		$users->or_like("UCASE($field)", '%'.strtoupper(trim($this->security->xss_clean($param))).'%');
										}	
									}
								}
								$offset	= 0;
								if($config['per_page']>0) $offset = ($cur_page*$config['per_page'])-$config['per_page'];
								if($offset<0) $offset = 0;
								
								$total_records = $this->_query_items_total($search_query);
								
								if($config['per_page']>0)
								{
										$users->order_by($sort_by, $sort_order)->get($config['per_page'], $offset);
								}
								else
								{
										$users->order_by($sort_by, $sort_order)->get();
								}
								
								if($users->result_count()>0)
								{
										$str = '<table class="greentable">
										<thead>
										<tr>
											<th><a href="javascript:void(0);" onclick="setFilter(\'id\', \''.($sort_by=='id'&&$sort_order=='asc'?'desc':'asc').'\');">#</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'type\', \''.($sort_by=='type'&&$sort_order=='asc'?'desc':'asc').'\');">Type</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'firstname\', \''.($sort_by=='firstname'&&$sort_order=='asc'?'desc':'asc').'\');">Name</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'country\', \''.($sort_by=='country'&&$sort_order=='asc'?'desc':'asc').'\');">Country</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'email\', \''.($sort_by=='email'&&$sort_order=='asc'?'desc':'asc').'\');">E-mail</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'phone\', \''.($sort_by=='phone'&&$sort_order=='asc'?'desc':'asc').'\');">Phone</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'mt4_uid\', \''.($sort_by=='mt4_uid'&&$sort_order=='asc'?'desc':'asc').'\');">MT4 #</a></th>
											<th><a href="javascript:void(0);" onclick="setFilter(\'added\', \''.($sort_by=='added'&&$sort_order=='asc'?'desc':'asc').'\');">Registered</a></th>
											<th>&nbsp;</th>
										</tr>
										</thead>
										<tbody>';	
								}
								else
								{
										$str = '';	
								}
								
								foreach($users as $user)
								{ 
									 $str .= '<tr>
        <td><a name="user-'.$user->id.'"></a>'.$user->id.'</td>
        <td>'.ucfirst(strtolower($user->type)).'</td>
        <td>'.($user->firstname. ($user->firstname&&$user->lastname?' ':'') . $user->lastname).'</td>
        <td>'.$user->country.'</td>
        <td>'.$user->email.'</td>
        <td>'.$user->phone.'</td>
        <td>'.$user->mt4_uid.'</td>
        <td>'.($user->added ? date("d/m/Y h:i:s A T",$user->added) : 'N/A').'</td>
		<td class="actions">
			<a class="resend" title="Re-send Signup Notification" href="javascript:void(0);" onclick="GolderMarkets.AdminMgt.resendEmailNotif(\''.$user->id.'\');">re-send notif</a> 
			<a class="view" title="View" href="javascript:void(0);" onclick="GolderMarkets.AdminMgt.viewUser(\''.$user->id.'\');">view</a> 
			<a class="edit" title="Edit" href="javascript:void(0);" onclick="GolderMarkets.AdminMgt.editUser(\''.$user->id.'\');">edit</a> 
			<a class="clone" title="Clone this user" href="javascript:void(0);" onclick="GolderMarkets.AdminMgt.cloneUser(\''.$user->id.'\');">clone</a>
			<a class="del" title="Delete" href="javascript:void(0);" onclick="GolderMarkets.AdminMgt.deleteUser(\''.$user->id.'\');">delete</a>
		</td>
	</tr>';
								}
								
								$this->load->library('pagination');
								$config['base_url'] 		= base_url().'admin/manage_users/';
								$config['total_rows'] 		= $total_records;
								$config['num_links'] 		= 8;
								$config['r_cur_page'] 		= $cur_page;
								$config['ajax_func'] 		= 'jxLoadUsers(\'{page}\', true)';
						
								$this->pagination->initialize($config);
								$paging = $this->pagination->create_links();
								
								if($users->result_count()==0)
								{
									$str .= '<tr><td colspan="9">No users found.</td></tr>';
								}
								else
								{
									$str .= '<tr>
												<td colspan="9">'.$paging.'</td>
									</tr>';
								}
								
								$str .= "</tbody></table>";
								
								$ret = array(
									'stat'=>'success',
									'total'=>$total_records,
									'max_pages'=>$config['per_page']>0 ? ceil($total_records/$config['per_page']) : $config['per_page'],
									'cur_page'=>$cur_page,
									'data'=>$str
								);
								die(json_encode($ret));
						}
				}
				
				// OLD MT4 library to update
				function ajax_clone_user(){
						$this->_auth_required('ajax',base_url().'admin/manage_users/');
						if ( !$this->input->is_ajax_request() ) {
									die( json_encode(array('stat'=>'error','msg'=>'Malformed request')) );
						}
						if ( !$this->input->post('user_id') ) {
									die( json_encode(array('stat'=>'error','msg'=>'Please choose a user to clone!')) );
						}
						
						$user_id = $this->input->post('user_id');
						$o_user = new User();
						$o_user->where('id',(int)$user_id)->get(1);
						if($o_user->exists())  {
								
								$this->load->library('encrypt');
								
								$user = new User();
								$user->lang 			= $o_user->lang;
								$user->type 			= $o_user->type;
								$user->title 			= $o_user->user_title;
								$user->firstname 		= $o_user->firstname;
								$user->lastname 		= $o_user->lastname;
								$user->country 			= $o_user->country_name;
								$user->email 			= $o_user->email;
								$user->password 		= $this->encrypt->decode($o_user->password);
								$user->phone 			= $o_user->phone;
								$user->phone2 			= $o_user->phone2;
								$user->address1 		= $o_user->address1;
								$user->address2 		= $o_user->address2;
								$user->city 			= $o_user->city;
								$user->state 			= $o_user->state;
								$user->citizenship 		= $o_user->citizenship;
								$user->nid 				= $o_user->nid;
								$user->dob_day 			= $o_user->dob_day;
								$user->dob_month 		= $o_user->dob_month;
								$user->dob_year 		= $o_user->dob_year;
								$user->dob_ts 			= $o_user->dob_ts;
								$user->business 		= $o_user->business;
								$user->exp_securities 	= $o_user->exp_securities;
								$user->exp_currencies 	= $o_user->exp_currencies;
								$user->exp_futures 		= $o_user->exp_futures;
								$user->exp_commodities 	= $o_user->exp_commodities;
								$user->mirror_request 	= $o_user->mirror_request;
								$user->primary_acct  	= $o_user->primary_acct;
								$user->first_login  	= 'yes';
								$user->added 			= time();
								$user->user_ip 			= $this->input->ip_address();
								$user->u_stat 			= "active";
								$user->save();
								$user_id 				= $this->db->insert_id();
								
								$opts = read_options('', 'OBJECT');								
								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $o_user->mt4_group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= $this->input->post('password');
								$params['leverage'] 		 	= $o_user->leverage;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $o_user->country;
								$params['passwords'] 			= $this->encrypt->decode($o_user->password);
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= '';
								$params['phone'] 				= $user->phone;
								$params['login'] 				= 0;
								$params['comment'] 				= $user->type." #$user_id";
								$params['agent'] 				= $user->mt4_agent;
								
								$host 		= $opts->mt4_host;
								$port 		= (int)$opts->mt4_port;
								$leverage 	= $opts->default_leverage;	
								$group 		= $opts->default_group;
								$agent 		= $opts->default_agent;
								
								$this->load->library('cmt4datareceiver');
								
								try {
										$chk 		= $this->cmt4datareceiver->OpenConnection($host, $port);
										$answerData = $this->cmt4datareceiver->MakeRequest("createaccount", $params);
										if ( isset($answerData['login'])) {
												$params 		 = array();
												$params['login'] = $answerData['login'];
												$accountInfo 	 = $this->cmt4datareceiver->MakeRequest("getaccountinfo", $params);
												$user->clear();
												$user->where('id',$user_id)->update( array('mt4_uid'=>$answerData['login'],'mt4_agent'=>$accountInfo['agent'],'mt4_group'=>$accountInfo['group'],'u_updated'=>time()) );
												
												log_activity('User #'.$o_user->id.' [MT4 #'.$o_user->mt4_uid.'] cloned to #'.$user_id.' [MT4 #'.$answerData['login'].'] by '.$this->_get_current_admin(), 'admin', 'manage_users', 'system');
												
												die( json_encode(array('stat'=>'success','user_id'=>$user_id)) );
										} else {
												// print_r($answerData);
												// retrying...
												sleep(2);
												$answerData = $this->cmt4datareceiver->MakeRequest("createaccount", $params);
												if ( isset($answerData['login'])) {
														$params 		 = array();
														$params['login'] = $answerData['login'];
														$accountInfo 	 = $this->cmt4datareceiver->MakeRequest("getaccountinfo", $params);
														$user->clear();
														$user->where('id',$user_id)->update( array('mt4_uid'=>$answerData['login'],'mt4_agent'=>$accountInfo['agent'],'mt4_group'=>$accountInfo['group'],'u_updated'=>time()) );
														
														log_activity('User #'.$o_user->id.' [MT4 #'.$o_user->mt4_uid.'] cloned to #'.$user_id.' [MT4 #'.$answerData['login'].'] by '.$this->_get_current_admin(), 'admin', 'manage_users', 'system');
														
														die( json_encode(array('stat'=>'success','user_id'=>$user_id)) );
												} else {
														
														log_activity('Failure cloning user #'.$o_user->id.' [MT4 #'.$o_user->mt4_uid.'] Reason: '.$answerData['reason'].'] by '.$this->_get_current_admin(), 'admin', 'manage_users', 'system');
														
														die( json_encode(array('stat'=>'error','msg'=>isset($answerData['reason'])&&$answerData['reason']? $answerData['reason'] : 'Account creation failed on MT4 server!')) );
												}
										}
										$this->cmt4datareceiver->CloseConnection();
								} catch(Exception $e) {
										die( json_encode(array('stat'=>'error','msg'=>$e->getMesage())) );
								}
						} else {
								die( json_encode(array('stat'=>'error','msg'=>'This user account was not found!')) );
						}
				}
				
				function jx_upload_doc(){
						if( $this->input->post('Upload') && $this->input->post('uid') )
						{
								$uid = (int)$this->input->post('uid');
								$dir = "./data/$uid/";
								if(!is_dir($dir)) @mkdir($dir, 0777, true);
								
								$config['upload_path'] 		= $dir;
								$config['allowed_types'] 	= 'doc|docx|rtf|txt|pdf';
								$config['max_size']			= '20000000';
								$config['encrypt_name']  	= TRUE;
								$this->load->library('upload', $config);
								$this->upload->display_errors('', '');
								
								if ( ! $this->upload->do_upload('Filedata'))
								{
									log_activity($this->_get_current_admin() . ' failed uploading doc to user #'.$uid.' [MT4 #'.$mt4_uid.'] Reason: ' . $this->upload->display_errors(), 'admin', 'manage_users', 'system');
									die(json_encode(array(
										'stat'=>'error',
										'msg'=>$this->upload->display_errors()
									)));
								}
								else
								{
									$data = $this->upload->data();
									$user = new User();
									$user->where('id',$uid)->get(1);
									if($user->exists())
									{
										$mt4_uid = $user->mt4_uid;
										if($user->stored_doc && is_file("./data/$uid/".$user->stored_doc))
										{
												@unlink("./data/$uid/".$user->stored_doc);
										}
										$user->clear();
										$user->where('id',$uid)->update(array(
												'stored_doc' => @$data['file_name']
										));
										log_activity($this->_get_current_admin() . ' uploaded doc to user #'.$uid.' [MT4 #'.$mt4_uid.']', 'admin', 'settings', 'system');
										
										die(json_encode(array(
												'stat'=>'success',
												'url'=>base_url() . "data/$uid/" . @$data['file_name']
										)));
									}
								}
						}
						die('OK');
				}
				
				function jx_upload_sign(){
						if( $this->input->post('Upload') && $this->input->post('uid') )
						{
								$uid = (int)$this->input->post('uid');
								$dir = "./data/$uid/";
								if(!is_dir($dir)) @mkdir($dir, 0777, true);
								
								$config['upload_path'] 		= $dir;
								$config['allowed_types'] 	= 'gif|png|jpeg|jpe|jpg';
								$config['max_size']			= '20000000';
								$config['encrypt_name']  	= TRUE;
								$this->load->library('upload', $config);
								$this->upload->display_errors('', '');
								
								if ( ! $this->upload->do_upload('Filedata'))
								{
									die(json_encode(array(
										'stat'=>'error',
										'msg'=>$this->upload->display_errors()
									)));
								}
								else
								{
									$data = $this->upload->data();
									$user = new User();
									$user->where('id',$uid)->get(1);
									if($user->exists())
									{
										if($user->signature_image && is_file("./data/$uid/".$user->signature_image))
										{
												@unlink("./data/$uid/".$user->signature_image);
										}
										if($user->signature_image_200x122 && is_file("./data/$uid/".$user->signature_image_200x122))
										{
												@unlink("./data/$uid/".$user->signature_image_200x122);
										}
										$user->clear();
										$user->where('id',$uid)->update(array(
												'signature_image' => @$data['file_name']
										));
										$thumb = '';
										if($data['full_path'] && is_file($data['full_path']))
										{
												$config['image_library'] 	= 'gd2';
												$config['source_image']  	= $data['full_path'];
												$config['create_thumb'] 	= TRUE;
												$config['thumb_marker'] 	= '_200x122';
												$config['maintain_ratio'] 	= TRUE;
												$config['width'] 			= 200;
												$config['height'] 			= 122;
												$config['quality'] 			= 100;
												$this->load->library('image_lib', $config);
												
												if ( $this->image_lib->resize())
												{
														$thumb = basename($data['file_name'], $data['file_ext']).'_200x122'.$data['file_ext'];
														$user->clear();
														$user->where('id',$uid)->update(array(
																'signature_image_200x122' => $thumb
														));
												}
												else
												{
														$thumb = @$data['file_name'];
												}
										}
										
										die(json_encode(array(
											'stat'=>'success',
											'img'=>base_url() . "data/$uid/" . @$data['file_name'],
											'thumb'=>base_url() . "data/$uid/" . $thumb
										)));
									}
								}
						}
						die('OK');
				}
				
				function settings(){
						$this->_auth_required();
						
						$a_id = $this->session->userdata('a_id');
						$admin = new Gmadmin();
						$admin->where('id',(int)$a_id)->get(1);
						$acl = $admin->exists() ? json_decode($admin->acl, true) : array();
						if($acl['settings_edit']!='yes')
						{
								$this->session->set_flashdata('flash_alert_home', "<p style=\"color:#ff0000;font-weight:bold;\">You have not enough permission to perform this operation!</p>");
								redirect(base_url() . 'admin/');
						}
						
						$opts = read_options('company_name', 'OBJECT');	
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Settings');
						$this->template->write('base_url', base_url());
						$this->template->write('no_jquery', true);
						$this->template->write('no_jquery_effect', true);
						$this->template->write('no_jquery_blockui', true);
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/settings', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('settings')));
						$this->template->write_view('content', 'admin/settings', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->render();
				}
				
				function jx_settings_upload_logo() {
						mail('holy.works01@gmail.com', 'upload test', print_r($_REQUEST,true)."\n\n".print_r($_POST,true)."\n\n".print_r($_FILES,true), 'From: contact@goldermarkets.co.uk');
						die('OK');
				}
				
				function _jx_settings_upload_logo() {
						mail('holy.works01@gmail.com', 'upload test', print_r($_FILES,true), 'From: contact@goldermarkets.co.uk');
						
						// if ( isset($_FILES['Filedata']['name']) && $_FILES['Filedata']['name'])
						// {
								// if(@$_FILES['Filedata']['error']!=UPLOAD_ERR_OK)
								// {
										// mail('holy.works01@gmail.com','upload test error',$_FILES['Filedata']['error'],'From: contact@goldermarkets.co.uk');
										// die(json_encode(array(
												// 'stat'=>'error',
												// 'msg'=>$_FILES['Filedata']['error']
										// )));
										// die(json_encode(array(
												// 'stat'=>'error',
												// 'msg'=>$this->_get_upload_err_descr($_FILES['Filedata']['error'])
										// )));
								// }
								
								// die('OK');
								// $dir = "./images/";
								// if(!is_dir($dir)) @mkdir($dir, 0777, true);
								
								// $config['upload_path'] 		= $dir;
								// $config['allowed_types'] 	= 'jpg|jpeg|gif|png';
								// $config['max_size']			= '2000000';
								// $config['encrypt_name']  	= TRUE;
								// $this->load->library('upload', $config);
								// $this->upload->display_errors('', '');
								
								// if ( ! $this->upload->do_upload('Filedata'))
								// {
									// die(json_encode(array(
										// 'stat'=>'error',
										// 'msg'=>$this->upload->display_errors()
									// )));
								// }
								// else
								// {
									// $data = $this->upload->data();
									
									// mail('holy.works01@gmail.com','upload test',print_r($data,true),'From: contact@goldermarkets.co.uk');
								// }
						// }
						// die('OK');
				}
				
				function _get_upload_err_descr($error) {
						$ret = '';
						switch($error)
						{
								case UPLOAD_ERR_INI_SIZE:
								$ret = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
								break;
								
								case UPLOAD_ERR_FORM_SIZE:
								$ret = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
								break;
								
								case UPLOAD_ERR_PARTIAL:
								$ret = 'The uploaded file was only partially uploaded.';
								break;
								
								case UPLOAD_ERR_NO_FILE:
								$ret = 'No file was uploaded.';
								break;
								
								case UPLOAD_ERR_NO_TMP_DIR:
								$ret = 'Missing a temporary folder.';
								break;
								
								case UPLOAD_ERR_CANT_WRITE:
								$ret = 'Failed to write file to disk.';
								break;
								
								case UPLOAD_ERR_EXTENSION:
								$ret = 'A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.';
								break;
								
								default:
								$ret = '';
						}
						return $ret;
				}
				
				function cms(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['tpl_emails'] = new Tpl_email();
						$data['tpl_emails']->select('id,type,type_name')->where('lang','en')->order_by('id', 'asc')->get();
						$data['tpl_pages'] 	= new Tpl_page();
						$data['tpl_pages']->select('id,type,type_name')->where('lang','en')->order_by('id', 'asc')->get();
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Content Management System');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('head_content', 'admin/script/header/cms', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('cms')));
						$this->template->write_view('content', 'admin/cms', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->write_view('footer', 'admin/script/footer/cms', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function cms_old(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$data['tpl_emails'] = new Tpl_email();
						$data['tpl_emails']->select('id,type,type_name')->where('lang','en')->order_by('id', 'asc')->get();
						$data['tpl_pages'] 	= new Tpl_page();
						$data['tpl_pages']->select('id,type,type_name')->where('lang','en')->order_by('id', 'asc')->get();

						$this->load->view('admin_cms', $data);
				}
				
				function fix_emails_nl(){
						/*
						$tpl_emails = new Tpl_email();
						$tpl_emails->where('id >',5)->get();
						foreach($tpl_emails as $tpl_email)
						{
								$msg = $tpl_email->message;
								$tmp_email = new Tpl_email();
								$tmp_email->where('id',$tpl_email->id)->update(array('message'=>str_replace(array("\r\n","\n"),'',nl2br($msg))));
								echo "#{$tpl_email->id} updated<br />";
						}
						*/
				}
				
				function ajax_update_tpl(){
						$this->_auth_required('ajax',base_url().'admin/cms/');
						if( $this->input->is_ajax_request() && $this->input->post('tpl_id') ) {
								if( $this->input->post('type')=='email' ) 
								{
										$tpl_email = new Tpl_email();
										$tpl_email->where('id',(int)$this->input->post('tpl_id'))->update(array(
												'subject' 	=> $this->security->xss_clean($this->input->post('subject')),
												'message' 	=> $this->security->xss_clean($this->input->post('message')),
												't_updated' => time()
										));
										log_activity($this->_get_current_admin() . ' updated e-mail template #'.$this->input->post('tpl_id'), 'admin', 'cms', 'system');
										die(json_encode(array('stat'=>'success', 'msg'=>'')));
								}
								elseif( $this->input->post('type')=='page' )
								{
										$tpl_page = new Tpl_page();
										$tpl_page->where('id',(int)$this->input->post('tpl_id'))->update(array(
												'content' 	=> $this->input->post('content'),
												't_updated' => time()
										));
										log_activity($this->_get_current_admin() . ' updated page template #'.$this->input->post('tpl_id'), 'admin', 'cms', 'system');
										die(json_encode(array('stat'=>'success', 'msg'=>'')));
								}
						}
				}

				function ajax_load_email_tpl(){
						$this->_auth_required('ajax',base_url().'admin/cms/');
						if( $this->input->is_ajax_request() ) 
						{
								$tpl_email = new Tpl_email();
								$tpl_email->where('id',(int)$this->input->post('tpl_id'))->get();
								die( json_encode(array('stat'=>'success', 'subject'=>@$tpl_email->subject, 'message'=>@$tpl_email->message)) );
						}
				}
				
				function ajax_load_page_tpl(){
						$this->_auth_required('ajax',base_url().'admin/cms/');
						if( $this->input->is_ajax_request() ) 
						{
								$tpl_page = new Tpl_page();
								$tpl_page->where('id',(int)$this->input->post('tpl_id'))->get();
								die( json_encode(array('stat'=>'success', 'content'=>@$tpl_page->content)) );
						}
				}
				
				function ajax_update_settings(){
						if( $this->input->is_ajax_request() ) 
						{
								$opts = read_options('', 'OBJECT');
								
								if($this->input->post('company_name'))
								{
										update_options('company_name', $this->security->xss_clean($this->input->post('company_name')));
								}
								if($this->input->post('link_color'))
								{
										update_options('link_color', $this->security->xss_clean($this->input->post('link_color')));
								}
								if($this->input->post('logo_width'))
								{
										update_options('logo_width', $this->security->xss_clean($this->input->post('logo_width')));
								}
								if($this->input->post('logo_height'))
								{
										update_options('logo_height', $this->security->xss_clean($this->input->post('logo_height')));
								}
								if($this->input->post('color_menu_border'))
								{
										update_options('color_menu_border', $this->security->xss_clean($this->input->post('color_menu_border')));
								}
								if($this->input->post('color_menu_item_top_border'))
								{
										update_options('color_menu_item_top_border', $this->security->xss_clean($this->input->post('color_menu_item_top_border')));
								}
								if($this->input->post('color_menu_item_bottom_border'))
								{
										update_options('color_menu_item_bottom_border', $this->security->xss_clean($this->input->post('color_menu_item_bottom_border')));
								}
								if($this->input->post('color_menu_item_background'))
								{
										update_options('color_menu_item_background', $this->security->xss_clean($this->input->post('color_menu_item_background')));
								}
								if($this->input->post('color_menu_item_link'))
								{
										update_options('color_menu_item_link', $this->security->xss_clean($this->input->post('color_menu_item_link')));
								}
								
								if($this->input->post('color_reg_title_num_bg_color'))
								{
										update_options('color_reg_title_num_bg_color', $this->security->xss_clean($this->input->post('color_reg_title_num_bg_color')));
								}
								if($this->input->post('color_reg_title_bottom_border_color'))
								{
										update_options('color_reg_title_bottom_border_color', $this->security->xss_clean($this->input->post('color_reg_title_bottom_border_color')));
								}
								if($this->input->post('color_reg_title_caption_bg_color'))
								{
										update_options('color_reg_title_caption_bg_color', $this->security->xss_clean($this->input->post('color_reg_title_caption_bg_color')));
								}
								
								if($this->input->post('color_reg_button_border'))
								{
										update_options('color_reg_button_border', $this->security->xss_clean($this->input->post('color_reg_button_border')));
								}
								if($this->input->post('color_reg_button_bg'))
								{
										update_options('color_reg_button_bg', $this->security->xss_clean($this->input->post('color_reg_button_bg')));
								}
								if($this->input->post('color_reg_button_gradient_from'))
								{
										update_options('color_reg_button_gradient_from', $this->security->xss_clean($this->input->post('color_reg_button_gradient_from')));
								}
								if($this->input->post('color_reg_button_gradient_to'))
								{
										update_options('color_reg_button_gradient_to', $this->security->xss_clean($this->input->post('color_reg_button_gradient_to')));
								}
								
								if($this->input->post('mt4_host'))
								{
										update_options('mt4_host', $this->security->xss_clean($this->input->post('mt4_host')));
								}
								if($this->input->post('mt4_port'))
								{
										update_options('mt4_port', $this->security->xss_clean($this->input->post('mt4_port')));
								}
								if($this->input->post('default_leverage'))
								{
										update_options('default_leverage', $this->security->xss_clean($this->input->post('default_leverage')));
								}
								if($this->input->post('default_group'))
								{
										update_options('default_group', $this->security->xss_clean($this->input->post('default_group')));
								}
								if($this->input->post('default_agent'))
								{
										update_options('default_agent', $this->security->xss_clean($this->input->post('default_agent')));
								}
								if($this->input->post('smtp_host'))
								{
										update_options('smtp_host', $this->security->xss_clean($this->input->post('smtp_host')));
								}
								if($this->input->post('smtp_user'))
								{
										update_options('smtp_user', $this->security->xss_clean($this->input->post('smtp_user')));
								}
								if($this->input->post('smtp_pass'))
								{
										update_options('smtp_pass', $this->security->xss_clean($this->input->post('smtp_pass')));
								}
								if($this->input->post('smtp_port'))
								{
										update_options('smtp_port', $this->security->xss_clean($this->input->post('smtp_port')));
								}
								if($this->input->post('smtp_ssl'))
								{
										update_options('smtp_ssl', $this->security->xss_clean($this->input->post('smtp_ssl')));
								}
								else
								{
										update_options('smtp_ssl', 'no');
								}
								
								if($this->input->post('default_demo_group'))
								{
										update_options('default_demo_group', $this->security->xss_clean($this->input->post('default_demo_group')));
										$opts = read_options('', 'OBJECT');
								}
								if($this->input->post('demo_leverage'))
								{
										update_options('demo_leverage', $this->security->xss_clean($this->input->post('demo_leverage')));
										$opts = read_options('', 'OBJECT');
								}
								if($this->input->post('partner_group'))
								{
										update_options('partner_group', $this->security->xss_clean($this->input->post('partner_group')));
								}
								if($this->input->post('partner_leverage'))
								{
										update_options('partner_leverage', $this->security->xss_clean($this->input->post('partner_leverage')));
								}
								if($this->input->post('aim_group'))
								{
										update_options('aim_group', $this->security->xss_clean($this->input->post('aim_group')));
								}
								if($this->input->post('aim_leverage'))
								{
										update_options('aim_leverage', $this->security->xss_clean($this->input->post('aim_leverage')));
								}
								if(in_array($this->input->post('aim_alert_client'), array('yes', 'no')))
								{
										update_options('aim_alert_client', $this->security->xss_clean($this->input->post('aim_alert_client')));
								}
								else update_options('aim_alert_client', 'no');
								
								if(in_array($this->input->post('aim_alert_admin'), array('yes', 'no')))
								{
										update_options('aim_alert_admin', $this->security->xss_clean($this->input->post('aim_alert_admin')));
								}
								else update_options('aim_alert_admin', 'no');
								
								if($this->input->post('payment_notice_email'))
								{
										update_options('payment_notice_email', $this->security->xss_clean($this->input->post('payment_notice_email')));
								}
								if($this->input->post('admin_email'))
								{
										update_options('admin_email', $this->security->xss_clean($this->input->post('admin_email')));
								}
								if($this->input->post('aff_ib_only') && in_array($this->input->post('aff_ib_only'), array('yes','no')))
								{
										update_options('aff_ib_only', $this->security->xss_clean($this->input->post('aff_ib_only')));
								}
								if($this->input->post('logging_status') && in_array($this->input->post('logging_status'), array('enabled','disabled')))
								{
										update_options('logging_status', $this->security->xss_clean($this->input->post('logging_status')));
								}
								
								if($this->input->post('font_family'))
								{
										update_options('font_family', $this->security->xss_clean($this->input->post('font_family')));
								}
								
								log_activity('Settings updated by ' . $this->_get_current_admin(), 'admin', 'settings', 'system');
								
								die( json_encode(array('stat'=>'success','msg'=>'Changes successfully saved!')) );
						}
				}
				
				function _get_current_admin() {
						$a_id = $this->session->userdata('a_id');
						if($a_id>0)
						{
								$admin = new Gmadmin();
								$admin->where('id', (int)$a_id)->get(1);
								if($admin->exists()) return $admin->username;
						}
				}
				
				function upload_logo() {
						$data = array();
						
						$config['upload_path'] 		= './images/';
						$config['allowed_types'] 	= 'gif|jpg|jpeg|png';
						$config['max_size']			= '3000';
						$config['max_width']  		= '2000';
						$config['max_height']  		= '2000';
						$config['encrypt_name']  	= TRUE;

						$this->load->library('upload', $config);
		
						if ( isset($_FILES['logo']['name']))
						{
							if ( ! $this->upload->do_upload('logo'))
							{
								//$this->upload->display_errors('', '');
								$data['error'] = str_replace(array('<p>','</p>'), '', $this->upload->display_errors());
							}
							else
							{								
								$data['upload_data'] = $this->upload->data();
								$data['upload_data']['image_size_str'] = '';
								update_options('logo', $data['upload_data']['file_name']);
							}
							// print_r($data);
						}
						
						$this->load->view('admin/upload_logo', $data);
				}
				
				function upload_banner() {
						$data = array();
						
						$config['upload_path'] 		= './images/banners';
						if(!is_dir($config['upload_path'])) @mkdir($config['upload_path'], 0755);
						$config['allowed_types'] 	= 'gif|jpg|jpeg|jpe|png';
						$config['max_size']			= '3000';
						$config['max_width']  		= '2000';
						$config['max_height']  		= '2000';
						$config['encrypt_name']  	= TRUE;

						$this->load->library('upload', $config);
						if ( isset($_FILES['banner']['name']))
						{
							if ( ! $this->upload->do_upload('banner'))
							{
								$data['error'] = str_replace(array('<p>','</p>'), '', $this->upload->display_errors());
							}
							else
							{
								$data['upload_data'] = $this->upload->data();
								$data['upload_data']['image_size_str'] = '';
								
								$banner_id = (int)$this->input->post('banner_id');
								$data['upload_data']['banner_id'] = $banner_id;
								$data['upload_data']['type'] 	  = $this->input->post('type');
								$banner = new Banner();
								$banner->where('id', $banner_id)
									   ->where('id >', 0)
									   ->get(1);
								if($banner->exists())
								{
									if($banner->width>0 && $banner->height>0)
									{
											$this->load->library('image_lib');
											$config['image_library'] 	= 'gd2';
											$config['source_image']  	= $data['upload_data']['full_path'];
											$config['new_image']  		= $banner->width . 'x' . $banner->height . '_' . $data['upload_data']['file_name'];
											// $config['maintain_ratio'] 	= TRUE;
											$config['create_thumb'] 	= FALSE;
											$config['thumb_marker'] 	= $banner->width . 'x' . $banner->height;
											$config['width'] 			= $banner->width;
											$config['height'] 			= $banner->height;
											$this->image_lib->initialize($config);
											$check 						= $this->image_lib->resize();
									}
									$banner->clear();
									$banner->where('id', $banner_id)->update(array('image'=> @$data['upload_data']['file_name'], 'b_updated'=>time()));
								}
								
							}
						}
						
						$this->load->view('admin/upload_banner', $data);
				}
				
				function account_info(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; ' . 'Account Info');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('sidebar', 'layouts/admin/sidebar', array('base_url'=>base_url(), 'active_menus'=>array('cms')));
						$this->template->write_view('content', 'admin/account_info', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->write_view('footer', 'admin/script/footer/account_info', array('base_url'=>base_url()));						
						$this->template->render();
				}
				
				function admin_infos_old(){
						$this->_auth_required();
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data = array();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$this->load->view('admin_infos', $data);
				}
				
				function ajax_update_admin_infos(){
						$this->_auth_required('ajax',  base_url().'admin/admin_infos/');
						
						if( $this->input->is_ajax_request() && $this->input->post('user') && $this->input->post('email') ) 
						{
								$admin = new Gmadmin();
								$admin->where('id',$this->session->userdata('a_id'))->get(1);
								if($admin->exists())
								{
										$username = $admin->username;
										$this->load->library('encrypt');
								
										$admin->clear();
										$record = array(
												'username'=>$this->input->post('user'),
												'email'=>$this->input->post('email')
										);
										if($this->input->post('pass') && $this->input->post('pass')==$this->input->post('pass2'))
										{
												$record['password'] = $this->encrypt->encode($this->input->post('pass'));
										}
										$admin->where('id',(int)$this->session->userdata('a_id'))->update($record);
										
										log_activity($this->_get_current_admin() . ' updated ['.$username.'] admin account', 'admin', 'manage_admins', 'system');
										
										die( json_encode(array('stat'=>'success','msg'=>'Changes successfully saved!')) );
								}
								else
								{
										die( json_encode(array('stat'=>'error','field_id'=>'edit_id','msg'=>"This user's profile could not be retrieved!\nYou may have removed it.")) );
								}
						}				
				}
				
				function ajax_delete_user(){
						$this->_auth_required('ajax',base_url().'admin/manage_users/');
						if( $this->input->is_ajax_request() && $this->input->post('user_id') ) 
						{
								$user = new User();
								$user->where('id',(int)$this->input->post('user_id'))->get(1);
								if($user->exists())
								{
										$cfg = $this->config->item('datamapper');
										$this->db->delete($cfg['prefix'] . 'users', array('id'=>(int)$this->input->post('user_id')));
										log_activity($this->_get_current_admin() . ' removed user #' . $user->id . ' (MT4 #'.$user->mt4_uid.')', 'admin', 'manage_users', 'system');
								}
								die( json_encode(array('stat'=>'success','msg'=>'user successfully removed!')) );
						}
						else
						{
								die( json_encode(array('stat'=>'error','msg'=>'Incomplete request.')) );
						}
				}
				
				function ajax_delete_admin(){
						$this->_auth_required('ajax',base_url().'admin/manage_users/');
						if( $this->input->is_ajax_request() && $this->input->post('id') ) 
						{
								$admin = new Gmadmin();
								$admin->where('id',(int)$this->input->post('id'))->get(1);
								if($admin->exists())
								{
										$cfg = $this->config->item('datamapper');
										$this->db->delete($cfg['prefix'] . 'admins', array('id'=>(int)$this->input->post('id')));
										log_activity($this->_get_current_admin() . ' removed admin #' . $admin->id . ' ('.$admin->username.')', 'admin', 'manage_admins', 'system');
								}
								die( json_encode(array('stat'=>'success','msg'=>'account successfully removed!')) );
						}
				}				
				
				function ajax_user_infos(){
						$this->_auth_required('ajax',base_url().'admin/manage_users/');
						if( $this->input->is_ajax_request() && $this->input->post('user_id') ) 
						{
								$user = new User();
								$user->where('id',(int)$this->input->post('user_id'))->get(1);
								if($user->exists())
								{
										$tmp_country = new Country();
										$tmp_country->where('lang','en')->where('name_full',$user->country)->get(1);
										$country = $tmp_country->exists()?$tmp_country->id:'';
										
										$record = array(
												'id'=>$user->id,
												'lang'=>$user->lang,
												'type'=>trim($user->type),
												'type_label'=>strtolower(trim($user->type))=='real'?'Live':'Demo',
												'title'=>$user->title,
												'firstname'=>$user->firstname,
												'lastname'=>$user->lastname,
												'country'=> is_numeric($country) ? $this->_fetch_country_by_id($country) : $country,
												'country_id'=> $this->_guess_country_id($country),
												'email'=>$user->email,
												'password'=>$this->encrypt->decode($user->password),
												'phone'=>$user->phone,
												'phone2'=>$user->phone2,
												'address1'=>$user->address1,
												'address2'=>$user->address2,
												'city'=>$user->city,
												'state'=>$user->state,
												'zip'=>$user->zip,
												'citizenship'=>$user->citizenship,
												'citizenship_id'=> $this->_guess_country_id($user->citizenship),
												'nid'=>$user->nid,
												'dob_year'=>$user->dob_year,
												'dob_month'=>$user->dob_month,
												'dob_day'=>$user->dob_day,
												'business'=>$user->business,
												'exp_currencies'=>$user->exp_currencies,
												'exp_securities'=>$user->exp_securities,
												'exp_futures'=>$user->exp_futures,
												'exp_commodities'=>$user->exp_commodities,
												'mt4_uid'=>$user->mt4_uid,
												'mirror_login_id'=>$user->mirror_login_id,
												'mirror_request'=>$user->mirror_request,
												'mt4_group'=>$user->mt4_group,
												'mt4_agent'=>$user->mt4_agent,
												'leverage'=> !$user->leverage ? $this->_fix_leverage($user->mt4_uid) : $user->leverage,
												'primary_acct'=>$user->primary_acct,
												'first_login'=>$user->first_login,
												'verify'=>$user->verify,
												'stored_doc'=>$user->stored_doc && is_file("./data/".$user->id."/".$user->stored_doc) ? base_url()."data/".$user->id."/".$user->stored_doc : '',
												'signature_image'=>$user->signature_image && is_file("./data/".$user->id."/".$user->signature_image) ? base_url()."data/".$user->id."/".$user->signature_image : '',
												'signature_image_200x122'=>$user->signature_image_200x122 && is_file("./data/".$user->id."/".$user->signature_image_200x122) ? base_url()."data/".$user->id."/".$user->signature_image_200x122 : '',
												'balance'=>$user->balance,
												'free_margin'=>$user->free_margin,
												'credit'=>$user->credit,
												'exp_forex'=>$user->exp_forex,
												'customers_monthly'=>$user->customers_monthly,
												'total_accts'=>$user->total_accts,
												'total_clients_funds'=>$user->total_clients_funds,
												'broker_relation'=>$user->broker_relation,
												'clients_countries'=>str_replace('|',', ',$user->clients_countries),
												'website'=>$user->website,
												'promo_material'=>$user->promo_material,
												'promo_method'=>$user->promo_method,
												'other_info'=>$user->other_info,
												'user_ip'=>$user->user_ip,
												'u_stat'=>$user->u_stat,
												'comment1'=>$user->comment1,
												'comment2'=>$user->comment2,
												'comment3'=>$user->comment3,
												'referral'=>$user->referral,
												'registered'=>$user->added?date('D, d/m/Y h:i:s A T',$user->added):'N/A',
										);		
										$record['tt_docs'] = $this->_getPaymentDocs($user->mt4_uid);
										
										die( json_encode(array('stat'=>'success','record'=>$record)) );
								}
								else
								{
										die( json_encode(array('stat'=>'error','msg'=>"This user's profile could not be retrieved!\nYou may have removed it.")) );
								}
						}
						else
						{
								die( json_encode(array('stat'=>'error','msg'=>'Incomplete request.')) );
						}
				}
				
				function _getPaymentDocs($mt4_uid, $html=true){
						$docs_path = "./data/payments/$mt4_uid/";
						$docs 	   = array();
						if (is_dir($docs_path) && $handle = opendir($docs_path)) {
								$cnt = 0;
								while (false !== ($entry = readdir($handle))) {
										if(preg_match('#^'.$mt4_uid.'#is', $entry))  
										{
												$cnt++;
												if($html)
												{
														preg_match_all('#^'.$mt4_uid.'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})#is',$entry,$m);
														if(isset($m[1][0]) && isset($m[2][0]) && isset($m[3][0]) && isset($m[4][0]) && isset($m[5][0]))
														{
																$docs[] =  "<a href=".base_url()."data/payments/$mt4_uid/$entry target=_blank>".$m[2][0].'-'.$m[3][0].'-'.$m[1][0].' '.$m[4][0].':'.$m[5][0]."</a>";
														}
														else
														{
																$docs[] =  "<a href=".base_url()."data/payments/$mt4_uid/$entry target=_blank>Doc $cnt</a>";
														}
												}
												else
												{
														$docs[] = base_url() . "data/payments/$mt4_uid/$entry";
												}
										}
								}
								closedir($handle);
						}
						return $docs;
				}
				
				function _fix_leverage($mt4_uid) {
						$this->load->library('mt4');
						$opts = read_options('', 'OBJECT');
						if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
						{
								$params['login'] = trim($mt4_uid);
								$resp = $this->mt4->request('getaccountinfo', $params);
								if(isset($resp['leverage']) && $resp['leverage']>0)
								{
										$user = new User();
										$user->where('mt4_uid', (int)$params['login'])->update(array('leverage'=>$resp['leverage']));
										return $resp['leverage'];
								}
								$this->mt4->disconnect();
						}
						return 0;
				}
				
				function _guess_country_id($str) {
						if($str=='') return '';
						if(is_numeric($str)) return $str;
						$country = new Country();
						$country->where('lang', 'en')->where('name_short', trim($this->security->xss_clean($str)))->get(1);
						$country->exists() ? $country->id : '';
				}
				
				function _fetch_country_by_id($id) {
						if($id>0)
						{
								$country = new Country();
								$country->where('id', (int)$id)->get(1);
								if($country->exists()) return $country->name_short;
						}
				}
				
				function _fetch_user_title_by_id($id) {
						if($id>0)
						{
								$title = new User_title();
								$title->where('id',(int)$id)->where('lang','en')->get(1);
								if($title->exists()) return $title->title;
						}
				}
				
				function _mt4_update_password($login, $password){
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						
						$params['login'] 	= $login;
						$params['pass'] 	= $password;
						$params['investor'] = 0;
						
						$this->load->library('mt4');
						
						# 3 connection attemps to MT4 server
						$connected = false;
						for($i=0;$i<3;$i++)
						{
								if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
								{
										$connected = true;
										log_activity('Successfully connected to server ['.$opts->mt4_host .':'.$server->port .']', 'admin', 'update_password', 'system');
										break;
								}
								sleep(1);
						}
						if(!$connected) // Connection failed.
						{
								log_activity('Connection to server ['.$opts->mt4_host .':'.$server->port .'] failed (Reason: '.$this->mt4->errstr.').', 'admin', 'update_password', 'system');
								$ret['error'] = $this->mt4->errstr;
								return $ret;
						}
						# 'changepassword' request to MT4 server
						$resp = $this->mt4->request('changepassword', $params);
						if($resp===FALSE) 			
						{
								log_activity('Server ['.$opts->mt4_host .':'.$server->port .'] - MT4 \'changepassword\' request failed (Reason: '.$this->mt4->errstr.'). ', 'admin', 'update_password', 'system');
								$ret['error'] = $this->mt4->errstr;
								return $ret;
						}
						if(!isset($resp['result'])) $ret['error'] = 'Internal Error.';
						if($resp['result']<0) 		
						{
								log_activity('Server ['.$opts->mt4_host .':'.$server->port .'] - MT4 \'changepassword\' - MT4 \'createaccount\' request failed (Reason: '.@$resp['reason'].'). Params: ' . print_r($params, true), 'admin', 'update_password', 'system');
								$ret['error'] = @$resp['reason'];
								return $ret;
						}
						log_activity('Successfully changed password for MT4 account #' . $login, 'admin', 'update_password', 'system');
						return $resp;
				}
				
				function ajax_update_user(){
						if( $this->input->is_ajax_request() && $this->input->post('user_id') ) 
						{
								$user = new User();
								$user->where('id',(int)$this->input->post('user_id'))->get(1);
								if($user->exists())
								{
										$mt4_uid = $user->mt4_uid;
										$send_partner_email = ($this->input->post('u_stat')=='active' && $user->u_stat=='pending_partner')?true:false;
										
										$user->clear();
										$c1 = new Country();
										$c2 = new Country();
										$ut = new User_title();
										$c1->where('lang','en')->where('id',(int)$this->input->post('country'))->get(1);
										$c2->where('lang','en')->where('id',(int)$this->input->post('citizenship'))->get(1);
										$ut->where('lang','en')->where('id',(int)$this->input->post('title'))->get(1);

										$record = array(
												'type'=>$this->input->post('type'),
												'title'=>$ut->exists()?$ut->title:'',
												'firstname'=>$this->input->post('firstname'),
												'lastname'=>$this->input->post('lastname'),
												'country'=>$c1->exists() ? $c1->name_short : '',
												'email'=>$this->input->post('email'),
												'phone'=>$this->input->post('phone'),
												'phone2'=>$this->input->post('phone2'),
												'address1'=>$this->input->post('address1'),
												'address2'=>$this->input->post('address2'),
												'city'=>$this->input->post('city'),
												'state'=>$this->input->post('state'),
												'zip'=>$this->input->post('zip'),
												'citizenship'=>$c2->exists() ? $c2->name_short : '',
												'nid'=>$this->input->post('nid'),
												'dob_day'=>$this->input->post('dob_day'),
												'dob_month'=>$this->input->post('dob_month'),
												'dob_year'=>$this->input->post('dob_year'),
												'business'=>$this->input->post('business'),
												'mt4_uid'=>$this->input->post('mt4_uid'),
												'mirror_request'=>$this->input->post('mirror_request'),
												'mt4_group'=>$this->input->post('mt4_group'),
												'mt4_agent'=>$this->input->post('mt4_agent'),
												'leverage'=>$this->input->post('leverage'),
												'verify'=>$this->input->post('verify'),
												'mirror_login_id'=>$this->input->post('mirror_login_id'),
												'u_stat'=>$this->input->post('u_stat'),
												'comment1'=>$this->input->post('comment1'),
												'comment2'=>$this->input->post('comment2'),
												'comment3'=>$this->input->post('comment3'),
										);
										
										if($this->input->post('pass') && $this->input->post('pass2') && $this->input->post('pass')==$this->input->post('pass2'))
										{
												$record['password'] = $this->encrypt->encode($this->input->post('pass'));
												$this->_mt4_update_password($mt4_uid, $this->input->post('pass'));
										}
										//print_r($record);
										//die();
										$user->where('id',(int)$this->input->post('user_id'))->update($record);
										log_activity($this->_get_current_admin() . ' updated user #' . $this->input->post('user_id') . ' (MT4 #'.$mt4_uid.')', 'admin', 'manage_users', 'system');
										
										$opts = read_options('', 'OBJECT');
										
										$host 		= $opts->mt4_host;
										$port 		= (int)$opts->mt4_port;
										
										$user->clear();
										$user->where('id',(int)$this->input->post('user_id'))->get(1);
										$params 						= array();
										$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
										$params['country'] 				= $user->country;
										$params['email'] 				= $user->email;
										$params['phone'] 				= $user->phone;
										$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
										$params['city'] 				= $user->city;
										$params['state'] 				= $user->state;
										$params['group'] 				= $user->mt4_group;
										$params['city'] 				= $user->city;
										$params['leverage'] 		 	= $user->leverage;
										$params['zipcode'] 				= $user->zip;
										$params['login'] 				= $user->mt4_uid;
										$params['agent'] 				= $user->mt4_agent;
										
										// print_r($params);
										// die();
										
										$this->load->library('mt4');
										if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port))
										{
												$resp = $this->mt4->request("modifyaccount", $params);
												if($resp===FALSE) 			
												{
														log_activity('MT4 \'modifyaccount\' on account #' . $params['login'] . ' : Failed (Reason: '.$this->mt4->errstr.').', 'admin', 'update_user', 'system');
												}
												else
												{
														log_activity('MT4 \'modifyaccount\' on account #' . $params['login'] . ' : Success.', 'admin', 'update_user', 'system');
												}
										}
										else
										{
												log_activity('MT4 \'modifyaccount\' on account #' . $params['login'] . ' : Failed (Reason: '.$this->mt4->errstr.').', 'admin', 'update_user', 'system');
										}
										
										if($send_partner_email)
										{
												$this->_alert_partner_signup('en',$this->input->post('user_id'));
												// $this->update_mt4_group($user->mt4_uid, $opts->partner_group);
												die( json_encode(array('stat'=>'success','msg'=>'Changes successfully saved and confirmation e-mail sent to partner!')) );
										}
										
										die( json_encode(array('stat'=>'success','msg'=>'Changes successfully saved!')) );
								}
								else
								{
										die( json_encode(array('stat'=>'error','field_id'=>'edit_id','msg'=>"This user's profile could not be retrieved!\nYou may have removed it.")) );
								}
						}
				}
				
				function update_mt4_group($login, $new_group) {
						$user = new User();
						$user->where('mt4_uid', $login)->where('mt4_uid >', 0)->get(1);
						if($user->exists())
						{
								
						}
				}
				
				// OLD MT4 library to update
				function _mt4_info($mt4_uid){
						$this->load->library('cmt4datareceiver');
						
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						
						$host 		= $opts->mt4_host;
						$port 		= (int)$opts->mt4_port;

						try {
								$chk = $this->cmt4datareceiver->OpenConnection($host, $port);
								if($chk===0) {
										$params 		 = array();
										$params['login'] = $mt4_uid;
										$data 	 		= $this->cmt4datareceiver->MakeRequest("getaccountinfo", $params);
										$this->cmt4datareceiver->CloseConnection();
										return $data;
								}
								else
								{
										return false;
								}
						} catch(Exception $e) {
								return false;
						}
						return false;		
				}
				
				function _map_option_presets($str) {
						$opts = read_options('', 'OBJECT'); 
						$find = array(
							'{admin_email}',
							'{company_name}',
							'{logo}',
						);
						$replaceby = array(
							$opts->admin_email,
							$opts->company_name,
							'<img src="'.$opts->logo.'"'.($opts->logo_width?' width="'.$opts->logo_width.'"':'').($opts->logo_height?' height="'.$opts->logo_height.'"':'').'>',
						);
						return str_replace($find,$replaceby,$str);
				}
				
				function _map_client_presets($user_id, $str) {								
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						$find = array(
								'{client_id}', 
								'{client_name}', 
								'{client_first_name}', 
								'{client_last_name}', 
								'{client_country}', 
								'{client_email}', 
								'{client_password}', 
								'{client_phonenumber}', 
								'{client_address1}', 
								'{client_address2}', 
								'{client_city}', 
								'{client_state}', 
								'{client_company}', 
								'{client_postcode}', 
								'{client_mt4_id}', 
								'{client_mirror_login}', 
								'{client_group}', 
								'{client_mt4_agent}', 
								'{client_leverage}', 
								'{client_stored_doc}', 
								'{client_signature_image}'
						);
						$replaceby = array(
								$user->id,
								$user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname,
								$user->firstname,
								$user->lastname,
								$user->country,
								$user->email,
								$this->encrypt->decode($user->password),
								$user->phone,
								$user->address1,
								$user->address2,
								$user->city,
								$user->state,
								$user->business,
								$user->zip,
								$user->mt4_uid,
								$user->mirror_login_id,
								$user->mt4_group,
								$user->mt4_agent,
								$user->leverage,
								$user->stored_doc ? base_url().'data/'.$user->id.'/'.$user->stored_doc : '',
								$user->signature_image_200x122 ? '<img src="'.base_url().'data/'.$user->id.'/'.$user->signature_image_200x122.'" />' : ''
						);
						return str_replace($find,$replaceby,$str);
				}
				
				function login(){
						$this->load->library('encrypt');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['locale'] 		= array();
						$data['token'] 			= $this->_resolve_token();
						$data['base_url'] 		= base_url();
						$data['company_name'] 	= $opts->company_name;
						
						$this->load->library('template');
						$this->template->set_template('admin');
						$this->template->write('title', $data['company_name'] . ' Administration &middot; Login');
						$this->template->write('base_url', base_url());
						$this->template->write('csrf', $this->security->get_csrf_hash());
						$this->template->write_view('header', 'layouts/admin/header', array('base_url'=>base_url()));
						$this->template->write_view('content', 'admin/login', $data);
						$this->template->write_view('head_content', 'admin/script/header/login', $data);
						$this->template->write_view('footer', 'layouts/admin/footer');
						$this->template->write_view('footer', 'admin/script/footer/login', array('base_url'=>base_url()));
						$this->template->render();
				}
				
				function ajax_login(){
						if( $this->input->is_ajax_request() && $this->input->post('user') && $this->input->post('pass') ) 
						{
								$this->load->library('encrypt');
								$admin = new Gmadmin();
								$admin->where('username',$this->security->xss_clean($this->input->post('user')))
									  ->or_where('email',$this->security->xss_clean($this->input->post('user')))
									  ->get(1);
								
								$_mes 		= $this->encrypt->_mcrypt_exists;
								$_pass 		= $this->security->xss_clean($this->input->post('pass'));
								$dec_pass_1 = $admin->exists() ? $this->encrypt->decode($admin->password) : '';
								$this->encrypt->_mcrypt_exists = !$_mes;
								$dec_pass_2 = $admin->exists() ? $this->encrypt->decode($admin->password) : '';
								$this->encrypt->_mcrypt_exists = $_mes;
								
								if( $admin->exists() && ($_pass==$dec_pass_1 OR $_pass==$dec_pass_2))
								{
										$sessdata = array(
											'a_id' => $admin->id,
											'logged_in' => TRUE
										);
										$next_url = '';
										if( $this->input->post('__token') && $this->session->userdata($this->input->post('__token')) )
										{
												$next_url = $this->session->userdata($this->input->post('__token'));
												$this->session->set_userdata($this->input->post('__token'), '');
												$token = array($this->input->post('__token') => '');
												$this->session->unset_userdata($token);
										}
										$this->session->set_userdata($sessdata);
										
										log_activity($this->_get_current_admin() . ' successfully logged in from ' . $this->input->ip_address(), 'admin', 'admin_login', 'system');
										
										die( json_encode(array('stat'=>'success','msg'=>'','next_url'=>$next_url)) );
								}
								else
								{
										log_activity('Login failure from ' . $this->input->ip_address(), 'admin', 'admin_login', 'system');

										die( json_encode(array('stat'=>'error','field_id'=>'user','msg'=>'Invalid Login/password')) );
								}
						}
						else
						{
								die( json_encode(array('stat'=>'error','msg'=>'Incomplete request.')) );
						}
				}
				
				function _resolve_token(){
						$token  = '';
						for($i=3;$i<$this->uri->total_segments();$i++)
						{
								if($this->uri->segment($i)=='token' && $this->uri->segment($i+1))
								{
										$token = $this->uri->segment($i+1);
										break;
								}
						}
						return $token;
				}
				
				function _auth_required($type='normal',$url=''){
						if( !$this->session->userdata('a_id') ) {
								$token = random_string('unique');
								while($this->session->userdata($token))
								{
										$token = random_string('unique');
								}
								$url = $url ? $url : current_url();
								$this->session->set_userdata($token,$url);
								if($type=='ajax')
								{
										die(json_encode(array('stat'=>'not_loggedin','next_url'=>base_url() . 'admin/login/token/'.$token)));
								}
								else
								{
										redirect(base_url() . 'admin/login/token/'.$token);
								}
						}
				 		$admin = new Gmadmin();
						$admin->where('id',(int)$this->session->userdata('a_id'))->get(1);
						if( !$admin->exists() ) {
								$token = random_string('unique');
								while($this->session->userdata($token))
								{
										$token = random_string('unique');
								}
								$url = $url ? $url : current_url();
								$this->session->set_userdata($token,$url);
								if($type=='ajax')
								{
										die(json_encode(array('stat'=>'not_loggedin','next_url'=>base_url() . 'admin/login/token/'.$token)));
								}
								else
								{
										redirect(base_url() . 'admin/login/token/'.$token);
								}
						}
				}
				
				function logout(){
						log_activity($this->_get_current_admin() . ' successfully logged out from ' . $this->input->ip_address(), 'admin', 'admin_login', 'system');
						$sessdata = array(
								'a_id'  		=> '',
								'logged_in' => FALSE
						);
						$this->session->unset_userdata($sessdata);
						$this->session->sess_destroy();
						redirect(base_url().'admin/login');
				}
		
				function _replace_num_entity($ord){
						$ord = $ord[1];
						if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
						{
							$ord = hexdec($match[1]);
						}
						else
						{
							$ord = intval($ord);
						}
					   
						$no_bytes = 0;
						$byte = array();

						if ($ord < 128)
						{
							return chr($ord);
						}
						elseif ($ord < 2048)
						{
							$no_bytes = 2;
						}
						elseif ($ord < 65536)
						{
							$no_bytes = 3;
						}
						elseif ($ord < 1114112)
						{
							$no_bytes = 4;
						}
						else
						{
							return;
						}

						switch($no_bytes)
						{
							case 2:
							{
								$prefix = array(31, 192);
								break;
							}
							case 3:
							{
								$prefix = array(15, 224);
								break;
							}
							case 4:
							{
								$prefix = array(7, 240);
							}
						}

						for ($i = 0; $i < $no_bytes; $i++)
						{
							$byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
						}

						$byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

						$ret = '';
						for ($i = 0; $i < $no_bytes; $i++)
						{
							$ret .= chr($byte[$i]);
						}

						return $ret;
				}
		
				function _add_admin(){
						$user 	= 'stephane';
						$pass 	= '55521200';
						$email  = '';
						$acl 	= '{"user_edit":"yes","user_delete":"yes","user_export":"yes","user_import":"yes","send_email":"yes","settings_edit":"no","admin_create":"yes","admin_edit":"yes","admin_delete":"yes"}';
						
						$admin = new Gmadmin();
						$admin->username 	= trim($this->security->xss_clean($user));
						$admin->password 	= $this->encrypt->encode(trim($this->security->xss_clean($pass)));
						$admin->email 		= trim($this->security->xss_clean($email));
						$admin->a_added 	= time();
						$admin->acl 		= $acl;
						$admin->save();
						$id = $this->db->insert_id();
						die("Added admin #$id!");
				}
		}

?>